1

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; ")
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Mitchell
  • 19
  • 2
  • The expression `StrLevel != "low" or "medium" or "high"` can be written more concisely as `StrLevel != "low" or "medium"`. – Chris Martin Apr 14 '16 at 00:41
  • The way you have it written now, it's an infinite loop, so `while True` or `while 1` is a much simpler way to do that... but I expect that's not what you're trying to do. – kindall Apr 14 '16 at 00:41
  • Possible duplicate of [How do I test one variable against multiple values?](http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values) – Chris Martin Apr 14 '16 at 00:44

2 Answers2

6

You can use not in.

while strLevel not in ["low", "medium", "high"]:
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Alright cheers, will make this the answer in 9 minutes or whatever it says that I can do it in. "You can accept this answer in 9 minutes" – Mitchell Apr 14 '16 at 00:41
  • @Mitchell this is "the answer" fyi. I'm not sure how the bytecode will disassemble (i.e. it might instantiate the list each loop). You can use the `dis` module to find out and, if effiency matters, it might be better to store the options as a variable before the loop. – Jared Goguen Apr 14 '16 at 00:58
  • @JaredGoguen How much could efficiency matter when you're just validating a user input? How many times do you think you're going to go through the loop before he gets the idea or gives up? – Barmar Apr 14 '16 at 01:02
  • It probably doesnt, which is why it was a comment, just to maybe help OP understand what's going on behind the scenes :) – Jared Goguen Apr 14 '16 at 01:12
0

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
Brian Cain
  • 14,403
  • 3
  • 50
  • 88