Can I shorten this very long elif chain?

76 views Asked by At
if p11 == "+":
    loc = 11
elif p12 == "+":
    loc = 12
elif p13 == "+":
    loc = 13
elif p14 == "+":
    loc = 14
elif p15 == "+":
    loc = 15

I need to have the above going from 11 until 55, so it would amazing if i could simplify it. Whatever number comes after the "p" in the variables is what loc is equal to.

And if it is possible can someone explain the reverse?

1

There are 1 answers

0
Asi On

I don't know why you would like something like this, but in any case, I think you are looking something like this:

# The input variable
p11 = '+'

# Calculation of output (loc)
for variable_name, variable_value in locals().items():
    # Checking the variable name and the variable value
    if variable_value == '+' and len(variable_name) == 3 and variable_name.startswith('p') and \
            variable_name[1:3].isdigit() and 11 <= int(variable_name[1:3]) <= 55:
        loc = variable_name[1:3]
        print(loc)
        break
else:
    print('no results!')