switch-case in python

Python is a great language if you’re coding to IoT (Internet of Things) like small devices. If you’re coming from another language though you might be surprised that it doesn’t include the classic switch-case statement construct like you’d find in JavaScript, for example.

Fortunately, I just managed to create something that seems to work and the syntax isn’t too far off from the expected.

def switch(key, default):
    case = {
        0.0: 'zero-point-zero',
        0.1: 'zero-point-one',
        0.2: 'zero-point-two',
        0.3: 'zero-point-three',
        0.4: 'zero-point-four'
    }
    return case.get(key, default)

print switch(0.1, 'Unknown')
Running this would produce “zero-point-one”. This isn’t as robust as JavaScript’s or C’s implementation but this can be adjusted for lambda functions in a similar fashion.

 

python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s