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":
        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/

相关文章:

python - 切片正则表达式反向引用?诺坎多?

python - python 从多个文件中读取行

python - TensorFlow 中出现错误

Python - 仅对某些字符串计算字符串的长度不准确

python - Flask-WTF : CSRF token missing

python - 无论顺序如何,都生成重复列表

python - 使用 Paramiko 通过 SSH 执行重启命令

python - 托普利兹矩阵的托普利兹矩阵

python - 如何在python中调用特定的csv字段值

python - 读取日志数据的二进制文件并使用 int 输出到新文件(python)