Is there a way to execute code in an if/elif structure so it evaluates all the code up to the elif? Here is an example:
i = 1 # this can be anything depending on what to user chooses
x = 5
y = 10
if i == 1:
z = x + y
elif i == 2:
# Here I want to return what would have happened if i == 1, in addition other stuff:
r = x^3 - y
elif i == 3:
# Again, execute all the stuff that would have happened if i == 1 or == 2, an addition to something new:
# execute code for i == 1 and i == 2 as well as:
s = i^3 + y^2
What I'm attemping to do is to avoid explicitly rewriting z = x + y in elif == 2 etc.. because for my application there are hundreds of lines of code to be executed (unlike this trivial example). I guess I could wrap these things in function and call them, but I'm wondering if there is a more concise, pythonic way of doing it.
EDIT: The responses here seem to be focusing on the if/elif part of the code. I think this is my fault as I must not be explaining it clearly. If i == 2, I want to execute all the code for i == 2, in addition to executing the code for i == 1. I understand that I can just put the stuff under i == 1 into the i == 2 conditional, but since it's already there, is there a way to call it without rewriting it?
elifwithif?i == 2then thei == 1block won't get hit.. still not what the OP wantselifwithifwill not help if the conditions are mutually exclusive. It looks like you would be better served by defining your actual conditions, which is to say not ifi < 2followed byi < 3followed byi < 4. In other words, it looks like you progressively add more detail asigets larger. Does this hold?==with>=. i.e. useif i >= 1etc for everything.z = x + yto execute, why have it inside anif-statementat all? Maybe I'm not understanding the question.