Python 如何测试变量不等于多个事物?
这是我的一段代码:Python 如何测试变量不等于多个事物?,python,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":
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子句。如果我有更多可接受的选择怎么办?有没有更好的办法来制定这个条款 您可以将逻辑推入循环,并替换
while choice != "1" and choice != "2" and choice != "3":
与
然后,初始行
choice=“
是不必要的。然后,在每个分支中,一旦你完成了你想做的事情,你就可以中断while
位可以通过检查元素是否在这样的选择列表中来重构,使它更干净
while choice not in [1, 2, 3]:
这是检查choice的值是否不是该列表中的元素,而str(choice)是否不在“123”中
…我想你可以使用一个包含所有可能选项的集合,并使用“in”表达式来判断while部分
至于if-else部分,打印(选择“it is!”)就可以了。当1是值时,可以使用字典将1映射到要执行的代码,依此类推。。。这样,您就可以摆脱ifs,您的代码可以通过简单地更新字典在将来支持其他值。至于while中的条件,您只需检查键是否在字典中。我认为这样做会更好
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"
我建议让它循环直到选择了一个有效的选项,然后返回所选的值
这意味着您的代码的其余部分不在中,而在中,使所有内容都保持整洁()
你总是要打印选择,“它是”
(?)还是这些真的是单独的情况?@hayden实际的代码是非常不同的,我只是简化了它以使问题更清楚。我意识到它被简化了(做得好),但我更多的是问:(如果1做f(),如果2做g(),…而不是如果1或2做f()).既然你接受了答案,这些就不可能是真正独立的案例:)@hayden:?我不是建议他从循环中删除代码。我在这里试图避免而不是True
,主要是因为我不想有无休止的循环,并且出于某种原因,我没有想到中断
。我将在我的代码中实际使用您的建议,尽管Suhail Patel的答案更适合这个问题。谢谢@M830078h:我使用这种成员资格测试的问题是,如果您决定添加一个新案例(比如“4”),那么现在您必须在两个地方添加它。这是一个干巴巴的(不要重复你自己)违规行为,当我犯下这些错误时,我通常会引入bug..请注意,在这里使用集合文字而不是列表文字({1,2,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"
def get_choice(options):
"""Given a list of options, makes the user select one.
The options must be strings, or they will never match (because raw_input returns a string)
>>> yn_choices = ['y', 'n']
>>> a = get_choice(options = yn_choices)
"""
prompt_string = "Pick " + ", ".join(options)
while True:
choice = raw_input(prompt_string)
if choice in options:
return choice
else:
print "Invalid choice"
# Prompt user for selection
choice = get_choice(["1", "2", "3"])
# Do stuff with choice...
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"