An IF statement is executed based on the occurrence of a certain condition. IF statements must begin with the keyword IF and terminate with the keyword END.
break does not break out of an if statement, but the nearest loop or switch that contains that if statement. The reason for not breaking out of an if statement is because it is commonly used to decide whether you want to break out of the loop .
In Python, the break statement provides you with the opportunity to exit out of a loop when an external condition is triggered. You'll put the break statement within the block of code under your loop statement, usually after a conditional if statement.
(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. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With