Home > Software design >  Simplifying if statements for project
Simplifying if statements for project

Time:10-26

I'm new to python and I need some help on this part of my project. How can I simplify this?

 if x == 'C':
    if y == 1:
        z = 1
    if y == 2:
        z = 2
    if y == 3:
        z = 3
    if y == 4:
        z = 1
    if y == 5:
        z = 2

CodePudding user response:

Using a dict as a switch statement:

switcher = {'C': {1: 1, 2: 2, 3: 3, 4: 1, 5: 2}, ...}

z = switcher[x][y]

CodePudding user response:

Taking into account the frequency of the resulting values, the condition can be set by the expression

if x == 'C' and 0 < y < 6:
    z = (y - 1) % 3   1

CodePudding user response:

in this case you can just use list:

C = [None,1,2,3,1,2]
if x == 'C':
    z=C[y]
  • Related