Python: break outside loop

Python: break outside loop

Because break cannot be used to break out of an if – it can only break out of loops. Thats 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?

break breaks out of a loop, not an if statement, as others have pointed out. The motivation for this isnt 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.

Python: break outside loop

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

Leave a Reply

Your email address will not be published.