在学习python语言中发现python中跳出循环有两种方法,分别是break和continue,但是两种方法的区别一直不太清楚,也没有找到一个比较明确的说明,经过自己实际编码对比,基本上掌握了用法。
首先,写一段python的循环代码,如下:
foods = ["apple", "banan","orange","pear"]
for fruit in foods:
if fruit == "banan":
print("No more banna please!")
print("Great, delicious " + fruit)
else:
print("I am so glad: No banan!")
print("Finally, I finished stuffing myself")
输出结果是:
Great, delicious apple
No more banna please!
Great, delicious banan
Great, delicious orange
Great, delicious pear
I am so glad: No banan!
Finally, I finished stuffing myself
然后,我们向其中加入break语句,看看结果是什么:
foods = ["apple", "banan","orange","pear"]
for fruit in foods:
if fruit == "banan":
print("No more banna please!")
break
print("Great, delicious " + fruit)
else:
print("I am so glad: No banan!")
print("Finally, I finished stuffing myself")
结果是:
Great, delicious apple
No more banna please!
Finally, I finished stuffing myself
在增加break之后,循环跳出了banan之后,直接输出到最后的语句,然后循环结束。那么,continue在循环中有什么作用的,试着用continue替代break,看一下结果是什么:
foods = ["apple", "banan","orange","pear"]
for fruit in foods:
if fruit == "banan":
print("No more banna please!")
continue
print("Great, delicious " + fruit)
else:
print("I am so glad: No banan!")
print("Finally, I finished stuffing myself")
结果是:
Great, delicious apple
No more banna please!
Great, delicious orange
Great, delicious pear
I am so glad: No banan!
Finally, I finished stuffing myself
可以看出,continue和break是有明显的区别的,只是循环到banan时,跳过,然后继续循环后面的部分,直到代码结束。