如何测试该变量不等于多个事物? [英] How to test that variable is not equal to multiple things?
本文介绍了如何测试该变量不等于多个事物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我拥有的一段代码:
This is the piece of code I have:
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 it works, I feel that it's really clumsy, specifically the while clause. What if I have more acceptable choices? Is there a better way to make the clause?
推荐答案
while
位可以稍微重构一下,通过检查元素是否在选择列表中来使其更简洁像这样
The while
bit could be refactored a little to make it a little bit cleaner by checking if the element is within a list of choices like so
while choice not in [1, 2, 3]:
这是检查选择的值是否不是该列表中的元素
This is checking if the value of choice is not an element in that list
这篇关于如何测试该变量不等于多个事物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文