DEV Community

Discussion on: I've never become overly convinced that switch statements are that much cleaner than `if else if else if else if else`

Collapse
 
lysofdev profile image
Esteban Hernández

How would you handle a default case in this?

My though is to add || defaultValue at the end since a failure to match any property will return undefined. Thoughts?

Collapse
 
yaser profile image
Yaser Al-Najjar • Edited

That would be handy using a try except:

def my_switcher(x):
    switches = {
        'a': 1,
        'b': 2,
    }
    default = 3

    try:
        result = switches[x]
    except KeyError:
        result = default

    return result



print(my_switcher('a'))
print(my_switcher('b'))
print(my_switcher('c'))

I added the extra default variable just to make the code self explanatory.

EDIT: Bad solution, look at the other comments.

Thread Thread
 
rhymes profile image
rhymes

You can also use defaultdict in the standard library :D

Thread Thread
 
pedromendes96 profile image
Pedro Mendes • Edited

This is clean :D

Thread Thread
 
lysofdev profile image
Esteban Hernández

This is the answer to this entire thread.

Thread Thread
 
yaser profile image
Yaser Al-Najjar

@rhymes and @pedromendes96 got it better than me 😁