pythonrubies
pythonrubies

Reputation: 273

How to check variable against 2 possible values?

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

Upvotes: 27

Views: 27842

Answers (7)

ofir_aghai
ofir_aghai

Reputation: 3311

short simple:

return s in ('a', 'b')

Upvotes: -2

Jesse Dhillon
Jesse Dhillon

Reputation: 7997

if s in ('a', 'b'):
    return 1
elif s in ('c', 'd'):
    return 2
else:
    return 3

Upvotes: 54

Tony Veijalainen
Tony Veijalainen

Reputation: 5555

Maybe little more self documenting using if else:

d = {'a':1, 'b':1, 'c':2, 'd':2} ## good choice is to replace case with dict when possible
return d[s] if s in d else 3

Also it is possible to implement the popular first answer with if else:

  return (1 if s in ('a', 'b') else (2 if s in ('c','d') else 3))

Upvotes: 1

Robert William Hanks
Robert William Hanks

Reputation: 361

return 1 if (x in 'ab') else 2 if (x in 'cd') else 3

Upvotes: 1

James
James

Reputation: 7198

 d = {'a':1, 'b':1, 'c':2, 'd':2}
 return d.get(s, 3)

Upvotes: 15

Tim Pietzcker
Tim Pietzcker

Reputation: 336178

if s in 'ab':
    return 1
elif s in 'cd':
    return 2
else:
    return 3

Upvotes: 1

Mad Scientist
Mad Scientist

Reputation: 18553

If you only return fixed values, a dictionary is probably the best approach.

Upvotes: 1

Related Questions