In yesterday's article: the end of the python while circulating article, we left a bug, when the conditions are met, the program enters an infinite loop, how to solve it?
To circumvent this problem, today introduced two key words: BREAK and the Continue .
A .break
If a break in the cycle, meaning that immediately jump out of this cycle, direct code demonstrates:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# !usr/bin/env python # -*- coding:utf-8 _*- """ @Author: Why grief @Blog (personal blog address): shuopython.com @WeChat Official Account (micro-channel public number): ape says python @Github:www.github.com
@File:break_continue.py @Time:2019/9/19 21:22
@Motto: short step a thousand miles, no small streams converge into a wonderful required the ocean, the program of life relentlessly accumulate! """
a = 0 the while True : # condition established forever, if not break, the cycle of death
a + = 1 # is equivalent to a = a + 1, the cumulative value of a constant plus 1 if a == 100 : BREAK # When a == 100, conditions are set up, break out of the loop, the program ends print("a = %d" % a)
print("循环结束,退出程序") |
输出结果:
1 2 3 4 5 6 7 8 9 10 |
a = 1 a = 2 a = 3 a = 4 .... a = 96 a = 97 a = 98 a = 99 循环结束,退出程序 |
上面程序是前一篇文章的代码,while True 死循环,当循环中的条件成立时,立即break退出循环。记住关键字break。
二.continue
如果在循环中使用 continue,意味着结束本次循环,继续下一次循环,直接代码演示:
1 2 3 4 5 6 7 8 9 10 |
a = 0 while True: # 条件永远成立
a += 1 # 等价 a = a + 1,a 的值不停的累计加 1 if a == 100: continue # 当a == 100 ,条件成立时,continue 继续下次一循环 print("a = %d" % a)
print("循环结束,退出程序") |
输出结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
a = 1 a = 2 a = 3 a = 4 ... a = 96 a = 97 a = 98 a = 99 a = 101 a = 102 a = 103 .... |
Program uses continue, into an infinite loop again, you noticed a small partner in the program printed to the console when, after 99 is 101, just not 100.
Because when a time value of 100 cycles continue executed, the program code will continue behind the skip codes, while loop back to the beginning .
The above also introduced the break and continue, to feel the difference between the two yet?
break is the end of the cycle, while the current sequential stop; continue is the end of this cycle, the next cycle to continue, in fact, the cycle has not stopped .
III. Key summary
while loop using break and continue keywords is essential, note the difference between the two
break: jump out of this cycle
continue: the end of this cycle, the next cycle continues
you may also like:
1.pycharm Configuration Template Development
2.python while loop
3.python for loop
Reproduced please specify : ape say Python »python loop using break / continue