this is just for academic interest. I encounter the following situation a lot.
either_true = False if x: ...do something1 either_true = True elif y: ...do something2 either_true = True if either_true: ..do something3
is there any pythonic way of doing it, or in general better programming way of doing it. Basically do something3 executes only if or elif is true.
elif ConditionThe elif block is executed if the specified condition evaluates to True .
The elif is short for else if. It allows us to check for multiple expressions. If the condition for if is False , it checks the condition of the next elif block and so on. If all the conditions are False , the body of else is executed.
The if-elif-else statement is used to conditionally execute a statement or a block of statements. Conditions can be true or false, execute one thing when the condition is true, something else when the condition is false. Contents: if statement.
If-elif-else statement is used in Python for decision-making i.e the program will evaluate test expression and will execute the remaining statements only if the given test expression turns out to be true. This allows validation for multiple expressions.
You could also omit the either_true
flag completely if doSomething3
is a single line of code (e.g. a function call):
if x: ..do something 1 ..do something 3 elif y: ..do something 2 ..do something 3
It maintains the nice property of evaluating x
and y
at most once (and y
won't be evaluated if x
is true).
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