Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check variable against 2 possible values?

Tags:

python

I have a variable s which contains a one letter string

s = 'a'

Depending on the value of that variable, I want to return different things. So far I am doing something along the lines of this:

if s == 'a' or s == 'b':
   return 1
elif s == 'c' or s == 'd':
   return 2
else: 
   return 3

Is there a better way to write this? A more Pythonic way? Or is this the most efficient?

Previously, I incorrectly had something like this:

if s == 'a' or 'b':
   ...

Obviously that doesn't work and was pretty dumb of me.

I know of conditional assignment and have tried this:

return 1 if s == 'a' or s == 'b' ...

I guess my question is specifically to is there a way you can compare a variable to two values without having to type something == something or something == something

like image 328
pythonrubies Avatar asked Sep 06 '25 18:09

pythonrubies


2 Answers

if s in ('a', 'b'):
    return 1
elif s in ('c', 'd'):
    return 2
else:
    return 3
like image 188
Jesse Dhillon Avatar answered Sep 10 '25 11:09

Jesse Dhillon


 d = {'a':1, 'b':1, 'c':2, 'd':2}
 return d.get(s, 3)
like image 36
James Avatar answered Sep 10 '25 13:09

James