我目前正在尝试使用漂亮的online tutorial site来教自己python。
我想出的解决方案是:
for numb in numbers:
if numb % 2 == 0:
print numb
if numb == 237:
break
哪个不起作用并向我抛出错误。正确的解决方案是
for number in numbers:
if number == 237:
break
if number % 2 == 1:
continue
print number
现在这看起来与我猜想的解决方案非常相似。我真的不明白我哪里出错了,它是对的。
我当然使用错误的数字%2
,但这应该只是结果中的错误,而不是整个工作中的错误。
我注意到的一件事是我没有使用“继续”这个词,我把break
放在最后 - 我想我们确实要检查237以查看它是否符合规则,然后是它之后的唯一数字我们不想要。
我也没有使用continue
,但即使我包含我的代码也无效。
continue
有什么意义?为什么我的尝试失败了?
答案 0 :(得分:2)
您的第一个版本正常,继续是不必要的:
>>> numbers = 2, 3, 4, 237, 5, 6
>>> for n in numbers:
... if n % 2 == 0:
... print(n)
... if n == 237:
... break
...
2
4
关键字continue
将中止当前循环迭代的完成,继续循环的下一次迭代。与break
对比,该{{1}}中止当前迭代并完全停止循环。