Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: 'break' outside loop

Tags:

python

in the following python code:

narg=len(sys.argv)
print "@length arg= ", narg
if narg == 1:
        print "@Usage: input_filename nelements nintervals"
        break

I get:

SyntaxError: 'break' outside loop

Why?

like image 605
Open the way Avatar asked Mar 17 '10 13:03

Open the way


People also ask

How do you break an outside loop in Python?

The Python "SyntaxError: 'break' outside loop" occurs when we use the break statement outside of a loop. To solve the error, use a return statement to return a value from a function, or use the sys. exit() method to exit the interpreter.

What does break outside loop in Python mean?

Sep 25, 2020. A break statement instructs Python to exit a loop. If you use a break statement outside of a loop, for instance, in an if statement without a parent loop, you'll encounter the “SyntaxError: 'break' outside loop” error in your code.

How do you put a break in outside the loop?

The break statement in Python is used to get out of the current loop. We can't use break statement outside the loop, it will throw an error as “SyntaxError: 'break' outside loop“. We can use break statement with for loop and while loops. If the break statement is present in a nested loop, it terminates the inner loop.

Can you use a keyword break outside of the loop?

Using break outside a loop or switch will result in a compiler error break cannot be used outside of a loop or a switch. As its name suggests, break statement terminates loop execution. It breaks the loop as soon as it is encountered.


3 Answers

Because break cannot be used to break out of an if - it can only break out of loops. That's the way Python (and most other languages) are specified to behave.

What are you trying to do? Perhaps you should use sys.exit() or return instead?

like image 131
Mark Byers Avatar answered Oct 19 '22 05:10

Mark Byers


break breaks out of a loop, not an if statement, as others have pointed out. The motivation for this isn't too hard to see; think about code like

for item in some_iterable:
    ...
    if break_condition():
        break 

The break would be pretty useless if it terminated the if block rather than terminated the loop -- terminating a loop conditionally is the exact thing break is used for.

like image 43
Mike Graham Avatar answered Oct 19 '22 05:10

Mike Graham


Because break can only be used inside a loop. It is used to break out of a loop (stop the loop).

like image 5
enricog Avatar answered Oct 19 '22 04:10

enricog