0

I'm writing a prime number checker. This is my code:

for num in range(10):
    if num > 1:
        for i in range(2, num):
            if (num % i) == 0:
                break
            else:
                print(num)

And the result is:

3
5
5
5
7
7
7
7
7
9

I found out that if I remove one indentation level of else such as:

for num in range(10):
    if num > 1:
        for i in range(2, num):
            if (num % i) == 0:
                break
        else:
            print(num)
            

the result is correct

2
3
5
7

Here is the real question. Shouldn't else be at the same indentation level as if? I am confused now.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
  • If else should always be at the same level if there is one. In your case your else block is not aligned with the first if block. Using an IDE with python plugin in it or using PyCharm will help. – Akash Ranjan Dec 24 '20 at 11:52
  • 2
    Read about [`for-else`](https://book.pythontips.com/en/latest/for_-_else.html) – Sociopath Dec 24 '20 at 11:52

1 Answers1

0

In Python there is concept loops with else block:

  • Inside loop execution, if a break statement not executed, then only else part will be executed.

  • else means loop without a break

  • Python allows the else keyword to be used with the for and while loops too. The else block appears after the body of the loop.

    for num in range(10):
        if num > 1:
            for i in range(2, num):
                if (num % i) == 0:
                    break
            else:
                print(num)
    

Here, It will print numbers until the break statement not executed.

Orion
  • 248
  • 3
  • 10