为什么这个 else 块可以工作,但它与 if 的情况不在同一级别?

Why does this `else` block work yet it is not on the same level as the `if` case?

此代码运行良好并生成了所需的素数列表。但是打印素数的 else 块出了问题,但它仍然有效,有人可以向我解释一下吗?

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

事实上,块for也有关键词else

for-else document

Python 有一个整洁的 for-else construct:

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 子句的一个常见用例是实现搜索循环;假设您正在搜索满足特定条件的项目,如果找不到可接受的值,则需要执行其他处理或引发错误。

参考https://shahriar.svbtle.com/pythons-else-clause-in-loops