较短的if语句

问题描述:

我觉得我如果statments太长,我怎么会缩短他们失望?:较短的if语句

userI = int(input("")) 

if userI == 1: 
    #code 
elif userI == 2: 
    #code 
elif userI == 3: 
    #code 
#ETC 
+0

您正在使用的,而不是比较运算赋值运算符。 – thefourtheye

+0

对所有分支执行相同的代码吗? – thefourtheye

+0

很难说没有看到执行什么代码,但是你可能会想用字典代替。 –

因为Python没有switch语句中有没有更好的方式来表示这一点。 如果没有看到代码的其余部分,很难说,但你可能会使它看起来更干净。

您似乎在问Python是否具有与case语句等价的功能。答案是不。你可以阅读关于为什么在PEP 3103

如果每个分支的代码能够被重构到一个单一的功能,你可以建一个表:

def func_1(): 
    pass 

def func_2(): 
    pass 

def func_3(): 
    pass 

def undefined_input(): 
    pass 

table = { '1': func_1, '2': func_2, '3': func_3 } 

userI = int(input("")) 
table.get(userI, undefined_input)()