mk8efz mk8efz - 4 months ago 10
Python Question

Python if/elif conditional

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?

Answer

Try this:

i = 1 # this can be anything depending on what to user chooses

x = 5
y = 10

if i >= 1:
    z = x + y

if i >= 2:
    # Here I want to return what would have happened if i == 1, in addition other stuff:
    r = x^3 - y

if 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
Comments