何时需要循环中的 else 语句

毫米

我对何时执行 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章