user2878311
user2878311

Reputation: 3

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

Upvotes: 0

Views: 118

Answers (3)

Nick
Nick

Reputation: 560

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"

Upvotes: 0

gefei
gefei

Reputation: 19766

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

Upvotes: 0

falsetru
falsetru

Reputation: 368944

("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"):
    ....

Upvotes: 3

Related Questions