Mohammad Taha
Mohammad Taha

Reputation: 15

how does the order of if conditions work in a while loop?

the link of code image is in the comment, check it to understand my question. i can't understand what's the difference between the commented out code and the if statement right above it. aren't they the same and shouldn't result be the same? but the commented out code gives correct result and not the one above it.

if string != "+" or string != "-" or string != "*" or string != "/" or string != "exit":
    print("invalid input")

elif string == "+" or string == "-" or string == "*" or string == "/" or string == "exit":
    break

even if i pass the appropriate string it generates invalid input and asks me to enter over and over again.

 if string == "+" or string == "-" or string == "*" or string == "/" or string == "exit":
    break

elif string != "+" or string != "-" or string != "*" or string != "/" or string != "exit":
    print("your input is wrong, please enter again:")

but using the code given above provides me with correct result.

Upvotes: 0

Views: 41

Answers (2)

Paritosh Singh
Paritosh Singh

Reputation: 6246

You are using an or with multiple != conditions. That boolean will always be true. consider

string = '+'
if string != "+" or string != "-": #False or True = True
    print(string != "+") #False
    print(string != "-") #true

The and keyword fits better

Upvotes: 0

Rocky Li
Rocky Li

Reputation: 5958

Your entire code should be shortened to:

bannedstring = ['+', '-', '*', '/', 'exit']
if string in bannedstring:
    break
else: # Use else not elif!
    print('invalid input')

There should never be more than 1 or in a line of code.

Upvotes: 1

Related Questions