How to exit an if clause
(This method works for if
s, multiple nested loops and other constructs that you can't 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
(Don't actually use this, please.)
while some_condition:
...
if condition_a:
# do something
break
...
if condition_b:
# do something
break
# more code here
break
You can emulate goto's functionality with exceptions:
try:
# blah, blah ...
# raise MyFunkyException as soon as you want out
except MyFunkyException:
pass
Disclaimer: I only mean to bring to your attention the possibility of doing things this way, while in no way do I endorse it as reasonable under normal circumstances. As I mentioned in a comment on the question, structuring code so as to avoid Byzantine conditionals in the first place is preferable by far. :-)