我对何时执行 else 子句感到困惑。我正在尝试编写一段代码来测试一个数字是否为质数。在我的“if”语句下,当 x%n==0 时,我打破了循环。else 语句还会运行吗?if...else..., for....else, while...else 的正确翻译是什么?我什么时候需要它?
def is_prime(x):
if x<2:
return False
if x==2:
return True
for n in range(2,x):
if x%n==0:
return False
break
else:
return True
else
如果循环在没有break
语句的情况下退出,则将进入循环上的子句。在 for 循环中,这通常意味着您迭代了最后一项。在while循环中,这意味着while“测试”失败。
一些有用的提示,可以避免对else
循环流的工作方式感到困惑:
else
则就像if
.while
循环因 while “测试”失败而终止,您可以想象在最后一次迭代while
中用 an替换关键字if
。将执行else 的示例:
for x in 'abc':
if x == 'z':
break
else:
# this will be executed, because we don't hit a break
for x in []:
break
else:
# this will be executed, because we don't hit a break
while False:
break
else:
# this will be executed, because we don't hit a break
不会执行else 的示例:
for x in 'abc':
if x == 'b':
break
else:
# this will not be executed, because we hit a break
n = 0
while True:
if n > 10:
break
n += 1
else:
# this will not be executed, because we hit a break
for x in 'abc':
if x == 'b':
return # assuming we're inside a function here
else:
# this will not be executed, because flow did not exit the loop
# (`for:else` is not like `finally`!)
while True:
pass
else:
# this will not be executed, and your CPU is overheating
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句