Switch in Python

后端 未结 7 1072
孤独总比滥情好
孤独总比滥情好 2021-01-01 22:34

I have tried making a switch like statement in python, instead of having a lot of if statements.

The code looks like this:

def findStuff(cds):
    L         


        
7条回答
  •  一生所求
    2021-01-01 23:27

    There's nothing wrong with a long if:

    if switch == 'case0':
       do_case0()
    elif switch == 'case1':
       do_case1()
    elif switch == 'case2':
       do_case2()
    ...
    

    If that's too long winded, or if you have a lot of cases, put them in a dictionary:

    switch = {'case0': do_case0, 'case1': do_case1, 'case2': do_case2, ...}
    switch[case_variable]()
    // Alternative:
    (switch[case_variable]).__call__()
    

    If your conditions are a bit more complex, you need to think a little about your data structures. e.g.:

    switch = {(0,21): 'never have a pension',
              (21,50): 'might have a pension',
              (50,65): 'definitely have a pension',
              (65, 200): 'already collecting pension'}
    for key, value in switch:
        if key[0] < case_var < key[1]:
            print(value)
    

提交回复
热议问题