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?

1
28
8/4/2016 11:45:11 AM

Accepted Answer

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?

55
3/17/2010 1:34:50 PM

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon