为什么这个“ else”块可以工作,但与“ if”情况不在同一个级别? [英] Why does this `else` block work yet it is not on the same level as the `if` case?

查看:112
本文介绍了为什么这个“ else”块可以工作,但与“ if”情况不在同一个级别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码运行得很好,并生成所需的质数列表。但是打印我们素数的 else 块是块状的,但是不管怎么说,有人可以向我解释吗?

This code runs pretty well and generates the wanted list of prime numbers. But the else block that prints our prime numbers is out of block, but it works anyway, can someone explain it to me?

for num in range(0, 100 + 1):
   # prime numbers are greater than 1
   if num > 1:
       for i in range(2, num):
           if (num % i) == 0:
               break
       else:
           print(num)

参考: programiz.com

推荐答案

Python整洁 for-else 构造

Python has a neat for-else construct:


For循环中还有一个else子句,我们大多数人都不熟悉。 else子句在循环正常完成时执行。这意味着循环没有遇到任何中断。

For loops also have an else clause which most of us are unfamiliar with. The else clause executes when the loop completes normally. This means that the loop did not encounter any break.

这篇关于为什么这个“ else”块可以工作,但与“ if”情况不在同一个级别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆