一、for循环
Python可以使用for语句遍历整个序列的值
for var in sequence
body
在for循环中,循环变量var遍历了队列中的每一个值,循环的语句体为每个值执行一次。
words=['cat','window','defensestrate']
for w in words:
print(w,len(w))
for循环求平均值:
n=eval(input("How many numbers?"))
sum=0.0
for i in range(n):
x=eval(input("Enter a number>>"))
sum=sum+x
print("\nThe average is",sum/n)
for循环是需要提供固定循环次数的循环方式。
二、while语句
while condition**:**
body
while语句中condition是布尔表达式。
break跳出最内层for/while循环。
sum=0
number=0
while number<20:
number+=1
sum+=number
if sum>100:
break
print("The number is",number)
print("The sum is",sum)
continue语句,起作用为结束本次循环,即跳出循环体中下面尚未执行的语句,对于while循环,继续求解循环条件。而对于for循环程序流程接着遍历循环列表。
for num in range(2,10):
if num%2==0:
print("Found an even number",num)
continue
print("Found a number",num)
运行结果:
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
代码桩:pass
例如:
for i in range(10):
pass
当你没想好这个循环执行什么操作时,你就可以用pass,用pass后这个循环会向下执行,只不过不进行任何操作,继续执行后面的语句。当你不知道没想到执行什么操作而又想执行后面的操作时就可以用pass。
三、for…else**:…和while…else:…语句与循环的搭配使用,**else:后的表达式在for循环列表遍历完毕后或while条件语句不满足的情况下执行,例如:
for n in range(2,10):
for x in range(2,n):
if n%x==0:
print(n,'equals',x,'*',n//x)
break
else:
print(n,'is a prime number')
运行结果:
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
四、交互式循环代码
def main():
sum=0.0
count=0
moredata="yes"
while moredata[0]=="y":
x=eval(input("Enter a number>>"))
sum=sum+x
count=count+1
moredata=input("Do you have more numbers(yes or no)?")
print("\nThe average of the number is",sum/count)
main()
运行结果:
Enter a number>>10
Do you have more numbers(yes or no)?y
Enter a number>>10
Do you have more numbers(yes or no)?y
Enter a number>>10
Do you have more numbers(yes or no)?n
The average of the number is 10.0
五、哨兵循环
设定一个哨兵值作为循环终止的标志,任何值都可以做哨兵,但要与实际数据有所区别
def main():
sum=0.0
count=0
x=eval(input("Enter a number(negative to quit)>>"))
while x>=0:
sum=sum+x
count=count+1
x=eval(input("Enter a number(negative to quit)>>"))
print("\n The average of the number is",sum/count)
main()
运行结果如下:
Enter a number(negative to quit)>>32
Enter a number(negative to quit)>>45
Enter a number(negative to quit)>>34
Enter a number(negative to quit)>>76
Enter a number(negative to quit)>>45
Enter a number(negative to quit)>>-1
The average of the number is 46.4
没有那么多yes/no的干扰,执行结果更加清晰
但不能包含负数的平均数计算,为了更加通用化需要引入字符串,可以用空字符串“”(引号中间没有空格)作为哨兵。
改进:
def main():
sum=0.0
count=0
xStr=input("Enter a number(<Enter> to quit)>>")
while xStr!="":
x=eval(xStr)
sum=sum+x
count=count+1
xStr=input("Enter a number(<Enter> to quit)>>)")
print("\nThe average of the number is",sum/count)
main()
运行结果:
Enter a number(<Enter> to quit)>>34
Enter a number(<Enter> to quit)>>23
Enter a number(<Enter> to quit)>>0
Enter a number(<Enter> to quit)>>-25
Enter a number(<Enter> to quit)>>-34.4
Enter a number(<Enter> to quit)>>22.7
Enter a number(<Enter> to quit)>>
The average of the number is 3.3833333333333333
六、文件循环
之前求平均数的数字都是用户输入的,如果几百个数求平均数,输入困难且容易出错。可以事先将数据录入到文件中,然后将这个文件作为程序的输入,避免人工输入的麻烦,便于编辑修改。
d:\file\math.txt这个文件中的内容如下:
25
25
300
100
def main():
fileName=input("what file are the numbers in?")
infile=open(fileName,'r')
sum=0
count=0
for line in infile:
sum=sum+eval(line)
count=count+1
print("\nThe average of the number is",sum/count)
main()
运行结果:
what file are the numbers in?d:\file\math.txt
The average of the number is 112.5
在这段代码中,循环变量line遍历文件的每一行,将每行都转换成数字然后加到sum中。
我们可以通过python的readline()来读取,readline()将文件的一行读取到字符串中。在文件尾部,readline()返回的一个空字符串可以作为哨兵值。python中采用readline()方法的end-of-file循环模式:
line=infile.readline()
while line!="":
#处理每一行
line=infile.readline()
文件循环求平均值:
def main():
fileName=input("what file are the numbers in?")
infile=open(fileName,'r')
sum=0.0
count=0
line=infile.readline()
while line!="":
sum=sum+eval(line)
count=count+1
line=infile.readline()
print("\nThe average of the number is",sum/count)
main()
运行结果:
what file are the numbers in?d:\file\math.txt
The average of the number is 112.5
七、嵌套循环:
之前实例中文件每行只存一个数字,这一次数字以逗号分割出现在文件的同一行上。
def main():
fileName=input("what file are the numbers in?")
infile=open(fileName,'r')
sum=0.0
count=0
line=infile.readline()
while line!="": #外循环:while语句对每行循环一次
for xStr in line.split(","): #内循环:for语句对一行中每个数字进行循环
sum=sum+eval(xStr)
count=count+1
line=infile.readline()
print("\nThe average of the number is",sum/count)
main()