Python - Imitating "else" in switch statements

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

How can I add the general case “Hey, this option does not exist”, similar to the Else query in the expression If, Elif, Else - something that runs if none of the If or Elif gets into work?

+6
source share
4 answers

You can catch a KeyError error that occurs when a value is not found on the map, and return or process the default value there. For example, with n = 3 this piece of code:

 if n == 1: print 'one' elif n == 2: print 'two' else: print 'too big!' 

Becomes as follows:

 choices = {1:'one', 2:'two'} try: print choices[n] except KeyError: print 'too big!' 

In any case, 'too big!' printed on the console.

+5
source

If else is really not an exception, is it 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! 
+7
source

The first article you contacted had a very clean solution:

 response_map = { "this": do_this_with, "that": do_that_with, "huh": duh } response_map.get( response, prevent_horrible_crash )( data ) 

This will call prevent_horrible_crash if response not one of the three options listed in response_map .

+1
source

Let's say you have a function f (a, b) and different parameter settings in accordance with the value of some variable x. So you want to execute f with a = 1 and b = 3 if x = 'Monday', and if x = 'Saturday', you want to execute f with a = 5 and b = 9. Otherwise, you will print, what is the value of x is not supported.

I would do

 from functools import partial def f(a,b): print("A is %s and B is %s" % (a,b)) def main(x): switcher = { "Monday": partial(f,a=1, b=3), "Saturday": partial(f, a=5, b=9) } if x not in switcher.keys(): print("X value not supported") return switcher[x]() 

thus f is not executed when the switch is declared, but on the last line.

0
source

All Articles