Mitchell
Mitchell

Reputation: 19

What's the best way to use "does not equal" in python?

Is there anything better I could use/import?

 while StrLevel != "low" or "medium" or "high":
        StrLevel = input("Please enter low, medium, or high for the program to work; ")

Upvotes: 1

Views: 120

Answers (2)

Brian Cain
Brian Cain

Reputation: 14619

Indeed, not in is recommended

But what does it mean to do the comparison you showed in the question?

>>> StrLevel = 'high'
>>> StrLevel != "low" or "medium" or "high"
True
>>> StrLevel = 'medium'
>>> StrLevel != "low" or "medium" or "high"
True
>>> StrLevel = 'low'
>>> StrLevel != "low" or "medium" or "high"
'medium'

...probably not at all what you might've expected.

To simplify it a bit:

>>> 'foo' != 'bar' or 'medium'
True
>>> 'foo' != 'foo' or 'medium'
'medium'
>>> False or 'medium'
'medium'

It's a bit confusing if you're not used to the boolean algebraic expressions in the languages that came before Python. Especially since Python goes to the trouble to make arithmetic comparisons meaningful when chained:

>>> x = 12
>>> 10 < x < 14
True
>>> 10 < x < 11
False

Upvotes: 0

Barmar
Barmar

Reputation: 781210

You can use not in.

while strLevel not in ["low", "medium", "high"]:

Upvotes: 6

Related Questions