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

本小妞迷上赌 提交于 2019-12-10 17:48:33

问题


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)

Reference: programiz.com


回答1:


Python has a neat 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.




回答2:


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 no acceptable value is found.

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




回答3:


In fact, block for also has key word else.

for-else document



来源:https://stackoverflow.com/questions/44560181/why-does-this-else-block-work-yet-it-is-not-on-the-same-level-as-the-if-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!