while循环
while :
Python会循环执行,直到不满足为止。
例如,计算数字0到1000000的和:
复制代码
1
2
3
4
5
6
7i = 0 total = 0 while i < 1000000: total += i i += 1 print(total)
之前提到,空容器会被当成 False ,因此可以用 while 循环来读取容器中的所有元素:
复制代码
1
2
3
4
5plays = set(['Hamlet', 'Macbeth', 'King Lear']) while plays: play = plays.pop() print ('Perform', play)
Perform King Lear
Perform Macbeth
Perform Hamlet
循环每次从 plays 中弹出一个元素,一直到 plays 为空为止。
for 循环
for in :
for 循环会遍历完中所有元素为止
上一个例子可以改写成如下形式:
复制代码
1
2
3
4plays = set(['Hamlet', 'Macbeth', 'King Lear']) for play in plays: print('Perform', play)
使用 for 循环时,注意尽量不要改变 plays 的值,否则可能会产生意想不到的结果。
之前的求和也可以通过 for 循环来实现:
复制代码
1
2
3
4
5total = 0 for i in range(100000): total += i print(total)
continue语句
同java c
break
同java c
else语句
与 if 一样, while 和 for 循环后面也可以跟着 else 语句,不过要和break一起连用。
- 当循环正常结束时,循环条件不满足, else 被执行;
- 当循环被 break 结束时,循环条件仍然满足, else 不执行。
不执行:
复制代码
1
2
3
4
5
6
7
8values = [7, 6, 4, 7, 19, 2, 1] for x in values: if x <= 10: print('Found:', x) break else: print('All values greater than 10')
Found: 7
执行:
复制代码
1
2
3
4
5
6
7
8values = [11, 12, 13, 100] for x in values: if x <= 10: print('Found:', x) break else: print ('All values greater than 10')
All values greater than 10
最后
以上就是壮观高跟鞋最近收集整理的关于python循环while循环for 循环continue语句breakelse语句的全部内容,更多相关python循环while循环for内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复