Python: 'break' outside loop

Question:

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?

Asked By: Open the way

||

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?

Answered By: Mark Byers

Because the break statement is intended to break out of loops. You don’t need to break out of an if statement – it just ends at the end.

Answered By: user180247

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

Answered By: enricog

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.

Answered By: Mike Graham

This is an old question, but if you wanted to break out of an if statement, you could do:

while 1:
    if blah:
        break
Answered By: Joshua Stafford
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.