简体   繁体   中英

Python “or” statement syntax not functioning?

I'm relatively new to python programming, anyway this is a small section from a larger piece of code. Which seems to be causing issues:

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")

Basically, I test the commands, and it only picks-up on the "Exit lift" command, and "Up", "Down", "1"...etc. won't work.

Any suggestions? beginner

("Exit lift" or "Up" or "Down" or "1" or "2" or "3" or "Cycle") is evaluated to 'Exit lift' .

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

So command != ("Exit lift" or "Up" or "Down" or "1" or "2" or "3" or "Cycle"): is equivalent to command != ("Exit lift") .

Use not in with sequence:

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

instead of

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

you should use

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

You could use an array, and use the in word

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

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

print "works"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM