'How to overcome indentation error in loops python code

n=int(input("enter any number="))
if n>1:
      for i in range(2,n):
           if(n%i==0):
                print("not prime")
                break
      else:
             print("prime")
             break
else:
    print("not prime")


Solution 1:[1]

Although your indentation is unfortunate (in that it makes your code hard to read, and most IDEs/linters will complain about it), it's not really the source of the error as far as whether or not the program runs correctly. If you run the exact code that you pasted into your question, you'll see the error:

SyntaxError: 'break' outside loop

This is because you have a break after the body of your for loop. Just remove it and the code will work. With the indentation aligned in a sane way, it should look like this:

n = int(input("enter any number="))
if n > 1:
    for i in range(2, n):
        if n % i == 0:
            print("not prime")
            break
    else:
        print("prime")
else:
    print("not prime")

The else: print("prime") block is part of the for statement, not the if statement inside the loop body of the for. The else block of a for ... else executes only if the loop runs to completion without a break -- in this case, you want to print prime only if you don't find any number (across the entire for loop) that proves it's not prime and breaks the loop.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1