这是我的一段代码:
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
位可以重构一点,通过检查元素是否在这样的选择列表中来使其更清晰一些
while choice not in [1, 2, 3]:
这是检查选择的值是否不是该列表中的元素
关于python - 如何测试该变量不等于多个事物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12553609/