Why does this `else` block work yet it is not on the same level as the `if` case?
本问题已经有最佳答案,请猛点这里访问。
这段代码运行得很好,生成了所需的素数列表。但是打印素数的
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)