较短的州议员

2024-03-28 11:04:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想如果我的座位太长了,我怎么能缩短呢?地址:

userI = int(input(""))

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

Tags: inputif地址etccodeintelif座位
3条回答

因为Python没有switch语句,所以没有更好的方法来表示这一点。 很难说没有看到代码的其余部分,但是您可以让它看起来更干净。你知道吗

如果可以将每个分支的代码重构为单个函数,则可以构建一个表:

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)()

您似乎在问Python是否有与case语句等价的语句。答案是否定的。你可以在PEP 3103中看到为什么。你知道吗

相关问题 更多 >