0

have just started learning python and this question came up to my mind is there a shorter way to determine if a string equals 'something' or 'somethingelse'?

example:

input = raw_input("question?")

while input != 'n' and input != 'y':
    #ask question again
Chemi
  • 13
  • 2

3 Answers3

5

You could check whether it is in a list or set.

input = raw_input("question?")

while input not in ['n', 'N']:
    #ask question again

If you are just trying to accept two cases though, you could also just call lower on the input.

while input.lower() != 'n':
    #ask question again
merlin2011
  • 71,677
  • 44
  • 195
  • 329
2

Perhaps unexpectedly, 'a' != input != 'b' works. It resolves the same way as ('a' != input) and ('b' != input). You can do the same thing with ==, or with <, >, etc. on numbers, as well.

Oh, but you have to be careful if you chain it longer than three things, or use multiple different comparison operators.

Vivian
  • 1,539
  • 14
  • 38
1

If it's a case issue, then you can:

while input.lower() != 'n'
Israel Unterman
  • 13,158
  • 4
  • 28
  • 35