如何测试变量不等于多个事物?Python

2024-05-23 15:17:58 发布

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

这是我的代码:

choice = ""

while choice != "1" and choice != "2" and choice != "3": 
    choice = raw_input("pick 1, 2 or 3")

    if choice == "1":
        print "1 it is!"

    elif choice == "2":
        print "2 it is!"

    elif choice == "3":
        print "3 it is!"

    else:
        print "You should choose 1, 2 or 3"

虽然它有效,但我觉得它真的很笨拙,特别是While子句。如果我有更多可接受的选择呢?有没有更好的方法来做这个条款?


Tags: orand代码youinputrawifis
3条回答

我想那样比较好

possilities = {"1":"1 it is!", "2":"2 it is!", "3":"3 it is!"} 
choice = ""

while True:
    choice = raw_input("pick 1, 2 or 3")
    if choice in possilities:
        print possilities[choice]
        break
    else:
        print "You should use 1, 2 or 3"

您可以将逻辑推入循环,并替换

while choice != "1" and choice != "2" and choice != "3": 

while True:

然后初始行choice = ""就不需要了。然后,在每个分支中,一旦完成了想做的事情,就可以break

可以对while位进行一些重构,通过检查元素是否在这样的选项列表中,使其更干净一些

while choice not in [1, 2, 3]:

这是检查是否选择的值不是该列表中的元素

相关问题 更多 >