3

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

Kaka Ruto
  • 4,581
  • 1
  • 31
  • 39

3 Answers3

6

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.

Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
1

In fact, block for also has key word else.

for-else document

Sraw
  • 18,892
  • 11
  • 54
  • 87
1

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

Akshay Apte
  • 1,539
  • 9
  • 24