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

+3


source to share


3 answers


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.

+6


source


In fact, the block for

also has a keyword else

.



for the else document

+1


source


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

+1


source







All Articles