python(五)——while循环
while循环
for循环用于针对集合中的每一个元素的代码块,而while循环会不断地运行,直到指定的条件不满足为止。
>>> current_number = 1
>>> while current_number <=5:
... print(current_number)
... current_number += 1
1
2
3
4
5
此处条件为current_number的值小于等于5时,就不断的循环下去。
若想控制退出的条件,可用标志来控制。
>>> current_number = 1
>>> active = True
>>> while active:
... print(current_number)
... current_number += 1
... if current_number > 5:
... active = False
1
2
3
4
5
此处active为标志,用于控制while循环的进行和退出。
break
break语句用于控制程序流程,当要立即退出while循环,不再运行循环中余下的代码,也不管条件测试结果如何时,可使用。
>>> current_number = 1
>>> while True:
... print(current_number)
... current_number += 1
... if current_number > 5:
... break
1
2
3
4
5
此处代码用break控制了循环的次数,在current_number大于5时执行break语句,退出while循环。
注:break语句只退出当前的代码块循环,而并非把嵌套的所有代码块循环退出,若要完全退出则要执行多次break语句。
continue语句
continue语句能够返回循环的开头,并根据条件测试结果决定是否继续执行循环。
以下代码输出了10以内的奇数,并使用了cuntinue语句让偶数不输出。
>>> number = 1
>>> while True:
... if number > 10:
... break
... if number%2 == 0:
... number += 1
... continue
... else:
... print(number)
... number += 1
1
3
5
7
9
while循环处理列表和字典
for循环是一种遍历列表的有效方式,但在for循环中不应修改列表,否则将导致python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,应该用while循环,通过while循环同列表和字典结合受用,可收集、存储并组织大量输入,供以后查看和显示。