Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - Simulating 'else' in dictionary switch statements

I'm working on a project which used a load of If, Elif, Elif, ...Else structures, which I later changed for switch-like statements, as shown here and here.

How would I go about adding a general "Hey, that option doesn't exist" case similar to an Else in an If, Elif, Else statement - something that gets executed if none of the Ifs or Elifs get to run?

like image 328
Joshua Merriman Avatar asked Mar 20 '13 02:03

Joshua Merriman


1 Answers

If the else is really not an exceptional situation, would it not be better to use the optional parameter for get?

>>> choices = {1:'one', 2:'two'}
>>> print choices.get(n, 'too big!')

>>> n = 1
>>> print choices.get(n, 'too big!')
one

>>> n = 5
>>> print choices.get(n, 'too big!')
too big!
like image 111
Ryan O'Neill Avatar answered Nov 15 '22 22:11

Ryan O'Neill