if or elif either true then do something
python, python-2.7
Solution
Your code is almost optimal, as far as code repetition and evaluation are concerned. The only thing I can think of to avoid repetition would be:
# be optimistic!
either_true = True
if x:
do_something1
elif y:
do_something2
else:
either_true = False
if either_true:
do_something3
This removes one assignment, although the total number of lines doesn't change.
The advantage is that this works with `n` conditions, without adding any other assignment, while your current solution requires an `either_true = True` for every condition.
In my opinion they have about the same degree of readability, but the above code will be better with more conditions.
Also there's no "pythonic" way other then a readable solution that avoids code repetition and is optimal in terms of efficiency, and I don't know of any kind of "better programming" to achieve the same result.
Problem
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.