python – How to exit an if clause
python – How to exit an if clause
(This method works for if
s, multiple nested loops and other constructs that you cant break
from easily.)
Wrap the code in its own function. Instead of break
, use return
.
Example:
def some_function():
if condition_a:
# do something and return early
...
return
...
if condition_b:
# do something else and return early
...
return
...
return
if outer_condition:
...
some_function()
...
from goto import goto, label if some_condition: ... if condition_a: # do something # and then exit the outer if block goto .end ... if condition_b: # do something # and then exit the outer if block goto .end # more code here label .end
(Dont actually use this, please.)
python – How to exit an if clause
while some_condition:
...
if condition_a:
# do something
break
...
if condition_b:
# do something
break
# more code here
break