Home > OS >  Python : 'break' outside loop Error in a While loop
Python : 'break' outside loop Error in a While loop

Time:10-17

I've researched this problem but can't find a solution. As far as I know, my break statement is in my while loop, but I still get the Syntax error.

entered_number = 1

while entered_number >=0 :
    entered_number = int(input ("Number to add :"))
    sum  = entered_number
    print("Entered number :",entered_number,"\nSum up til now:", sum)
else:
    print("The Final sum is :", sum)
    break

I know another solution to make my code work, but don't understand why this does not?

Thank you

CodePudding user response:

Actually I figured out that the else statement does not need break to get out of the loop...

CodePudding user response:

Your break statement is not inside the loop. It’s in the scope of the else statement, but not in the scope of your while loop

CodePudding user response:

A break statement must be inside a loop. In your example, it isn't, it's in the else block (the fact that the else is associated with a loop is inconsequential.

Then again, the else clause will only be executed once, so there isn't much of a point to having a break statement there anyway. Just remove it and you should be OK.

  • Related