1

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)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • Welcome to Stack Overflow! Please take the [tour]. What is this code supposed to do? Like, what is `goto`? What does the context look like? For more tips, see [ask]. From what you've posted, it looks like you could start by moving the `sleep(1)` after and use math to determine what number to pass to `goto()`, but I'll wait until you add more details before I post an answer. – wjandrea Nov 11 '21 at 02:12
  • Related, possible duplicate: [Replacements for switch statement in Python?](https://stackoverflow.com/q/60208/4518341) – wjandrea Nov 11 '21 at 02:17
  • goto is a function that I described. It would open the first file, second file, etc, and the number goes up to 30 eventually. – Devin Clark Nov 11 '21 at 02:17
  • @Devin Goes up to 30... OK, do all the `elif`s have `sleep(1)`? Is there an `else`? Ideally you'd provide a [mre]. – wjandrea Nov 11 '21 at 02:28

2 Answers2

1

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)
MYK
  • 1,988
  • 7
  • 30
-1

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.

enzo
  • 9,861
  • 3
  • 15
  • 38