Skip to content Skip to sidebar Skip to footer

Why Does This `else` Block Work Yet It Is Not On The Same Level As The `if` Case?

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 explai

Solution 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.


Solution 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


Solution 3:

In fact, block for also has key word else.

for-else document


Post a Comment for "Why Does This `else` Block Work Yet It Is Not On The Same Level As The `if` Case?"