#python学习笔记(五)#循环语句
目录
1 Updating variables
2 The while statement
3 Infinite loops
4 Definite loops using for
5 Examples:counting and summing loops
6 Examples:maximum and minimum loops
1 Updating variables
▲更新变量的值采用赋值语句
x = x + 1
▲被更新的变量需要有初始值initialize,否则会报错
>>> x = x + 1
NameError: name 'x' is not defined
2 The while statement
n = 5 #初始化迭代变量interation variable的值
while n > 0: #while+判断语句 为真时执行,否则进行下一个语句print(n) #缩进语句n = n - 1 #更新迭代变量,否则会无限循环成为 infinite loop
#执行一遍后回到while重新判断是否再次循环print('Blastoff!')
3 Infinite loops
This loop is obviously an infinite loop because the logical expression on the while statement is simply the logical constant True
无限循环while的判断语句为常数Ture
在主题语句中采用break来退出循环
while True:#infinite loopline = input('> ')if line == 'done':#如果用户输入'done'break #break退出语句print(line) #否则继续执行print
print('Done!')
运行结果
> hello there
hello there
> finished
finished
> done ##输入done时退出循环,运行下一条print语句
Done!
use the continue statement to skip to the next iteration without finishing the body of the loop for the current iteration.
continue用来开始新一轮循环,而不再执行本次循环的后续语句
while True:line = input('> ')if line[0] == '#': continue ##如果用户输入#开头,重新开始新一轮循环,不执行后续语句if line == 'done': break ##如果用户输入done,退出循环print(line)print('Done!')
运行结果
> hello there
hello there
> # don't print this ###以#开始,不进行后续print(line)语句
> print this!
print this!
> done
Done!
All
4 Definite loops using for
We call the while statement an indefinite loop because it simply loops until some condition becomes False, whereas the for loop is looping through a known set of items so it runs through as many iterations as there are items in the set.
while语句是不定循环,因为它循环直到判断语句为false
for是定循环,因为它的迭代变量是已知的确定数目的
friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends: #friend为迭代变量,依次遍历friends里的内容print('Happy New Year:', friend)print('Done!')
运行结果
Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Done!
5 Examples:counting and summing loops
###计数循环
count = 0 #初始化计数值
for itervar in [3, 41, 12, 9, 74, 15]:count = count + 1 #每循环一次,count+1print('Count: ', count)###求和循环
total = 0 #初始化
for itervar in [3, 41, 12, 9, 74, 15]:total = total + itervar #每循环一次,total加上新的数值print('Total: ', total)
6 Examples:maximum and minimum loops
#求最大值
largest = None
print('Before:', largest)for itervar in [3, 41, 12, 9, 74, 15]:if largest is None or itervar > largest :largest = itervarprint('Loop:', itervar, largest)print('Largest:', largest)#求最小值
smallest = None
print('Before:', smallest)for itervar in [3, 41, 12, 9, 74, 15]:if smallest is None or itervar < smallest:smallest = itervarprint('Loop:', itervar, smallest)print('Smallest:', smallest)
可以将该循环语句写成函数重复使用
def min(values): #参数为待比较的数据smallest = Nonefor value in values:if smallest is None or value < smallest:smallest = valuereturn smallest #返回计算出的最小值