I am writing a Python program but ended up having a bunch of if statements. Is there a way to shorten the code? Thanks in advance.
if val == M and time == p1:
goto(0)
sleep(1)
elif val == M and time == p2:
goto(1)
sleep(1)
elif val == M and time == p3:
goto(2)
sleep(1)
elif val == M and time == p4:
goto(3)
sleep(1)
elif val == M and time == p5:
goto(4)
sleep(1)
elif val == T and time == p1:
goto(5)
sleep(1)
elif val == T and time == p2:
goto(6)
sleep(1)
elif val == T and time == p3:
goto(7)
sleep(1)
elif val == T and time == p4:
goto(8)
sleep(1)
elif val == T and time == p5:
goto(9)
sleep(1)
CodePudding user response:
The code looks ok. Here are two alternatives:
Option 1: Use a dictionary
cases = {
(M, p1) : 1,
(M, p2) : 2,
(M, p3) : 3,
(M, p4) : 4,
(M, p5) : 5,
(T, p1) : 6,
(T, p2) : 7,
(T, p3) : 8,
(T, p4) : 9,
}
goto(cases[(val,time)])
sleep(1)
Option 2: Use case
statements (in Python 3.10 and beyond)
Hidden option: Find some other logic that achieves what you want.
eg.
if val in [T,M] and time in [p1,p2,p3,p4,p5]:
num = (val==T)*5 [p1,p2,p3,p4,p5].index(time) 1
goto(num)
sleep(1)
CodePudding user response:
This can get you started. You can store variables in a tuple and use a loop index to access them, together with integer division and remainder:
lvalues = ('M', 'T')
rvalues = ('p1', 'p2', 'p3', 'p4', 'p5')
for i in range(9):
lvalue = lvalues[i // 5]
rvalue = rvalues[i % 5]
print(f'val == {lvalue} and time == {rvalue}')
This outputs
val == M and time == p1
val == M and time == p2
val == M and time == p3
val == M and time == p4
val == M and time == p5
val == T and time == p1
val == T and time == p2
val == T and time == p3
val == T and time == p4
Save your variables inside lvalues
and rvalues
.