Why is this `else` block not working at the same level as the` if` yet?
This code works pretty well and generates the required list of prime numbers. But the block else
that prints our primes is out of order, but it still works, can someone explain this 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)
Link: programiz.com
source to share
Python has a neat for-else
construct :
There is also an else clause for loops, which most of us are not familiar with. The else clause is executed when the loop completes normally. This means that there was no break in the loop.
source to share
A common use case for an else clause in loops is to implement search loops; Let's say you are looking for an element that matches a certain condition and needs to do additional processing or throw an error if no acceptable value is found.
refer to https://shahriar.svbtle.com/pythons-else-clause-in-loops
source to share