1

I would like to understand why the following python code to find all prime numbers less than n works:

def prime(n):
    for q in range(2,n):
        for i in range(2,q):
            if q%i==0:
                print(q, "is not a prime")
                break
        else:
            print(q, "is a prime")

My problem is that I thought the else: should be aligned under the if: but it isn't in this code. I think the problem is that I do not understand well enough what the "break" does.

wim
  • 338,267
  • 99
  • 616
  • 750
Valerio
  • 189
  • 10
  • The shown code should lead to indentation error already on the first `for q ...` line. – Some programmer dude Jul 07 '21 at 15:21
  • 1
    Python also has `for-else`, see e.g. [here](https://stackoverflow.com/q/9979970/1639625) – tobias_k Jul 07 '21 at 15:22
  • 4
    It is mentioned here https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops – Vishnudev Krishnadas Jul 07 '21 at 15:22
  • Seems like an error-prone feature that could lead to many bugs. Why not use a different keyword? – h0r53 Jul 07 '21 at 15:23
  • Please refresh [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). And please make sure that your [mcve] doesn't contain unrelated problems, a good example should be able to be copy and pasted directly to replicate the problem being asked about without the need for us to edit it. – Some programmer dude Jul 07 '21 at 15:55

1 Answers1

3

In Python, for loops can also have an else: block (see for_stmt in the parser grammar). The else block of a for loop is entered if the loop runs to completion without hitting any break statement.

In your case, the break is conditional upon q % i == 0, so the else block here means that no number in range(2, q) has satisfied this condition, i.e. that q has no divisors besides 1 and itself.

Note: this primality test is very similar to a code snippet from the tutorial.

wim
  • 338,267
  • 99
  • 616
  • 750
  • wow, been coding python for a while but I never knew that for loops could have an else block! thanks for that answer – zanga Jul 07 '21 at 15:23