关于python:为什么这个`else`块工作但它与`if`情况不在同一级别?

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

本问题已经有最佳答案,请猛点这里访问。

这段代码运行得很好,生成了所需的素数列表。但是打印素数的else块是块外的,但是它还是可以工作的,有人能给我解释一下吗?

1
2
3
4
5
6
7
8
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)

参考:programmiz.com


(P)Python has a Neat EDOCX1 logical 2nd Construct:(p)布尔奇1


(P)a common use case for the ELSE clause in loops is to implement search loops;say you're performing a search for an item that meets a particular condition,and need to perform additional processing or raise an error if not acceptable value is found.(p)(P)Refer https://shahriar.svbtle.com/pytons-else-clause-in-loops(p)


(P)事实上,Block EDOCX1(英文)也有Key Word EDOCX1(英文)(p)(P)For-else document(p)