Python“或”语句语法不起作用?

时间:2013-10-14 09:38:07

标签: python

我对python编程比较陌生,无论如何这只是一段代码中的一小部分。这似乎导致了问题:

command = input("Command: ")

while command != ("Exit lift" or "Up" or "Down" or "1" or "2" or "3" or "Cycle"):
    print("Error: Command entered doesn't match the 'Commands' list, or isn't a possible command at this time! Please try again...")
    command = input("Command: ")

print ("Works")

基本上,我测试命令,它只选择“退出提升”命令,“向上”,“向下”,“1”等等。不行。

有什么建议吗?初学者

3 个答案:

答案 0 :(得分:3)

("Exit lift" or "Up" or "Down" or "1" or "2" or "3" or "Cycle")评估为'Exit lift'

>>> ("Exit lift" or "Up" or "Down" or "1" or "2" or "3" or "Cycle")
'Exit lift'

因此command != ("Exit lift" or "Up" or "Down" or "1" or "2" or "3" or "Cycle"):相当于command != ("Exit lift")

not in与序列一起使用:

while command not in ("Exit lift", "Up", "Down", "1", "2", "3", "Cycle"):
    ....

答案 1 :(得分:0)

而不是

while command != ("Exit lift" or "Up" or "Down" or "1" or "2" or "3" or "Cycle"):

你应该使用

while not command in ("Exit lift", "Up", "Down", "1", "2", "3", "Cycle"):

答案 2 :(得分:0)

您可以使用数组,并使用in

allowed = ["Exit lift", "Up", "Down", "1", "2", "3", "Cycle"]

while command not in allowed:
    print "not allowed!"

print "works"