switch case in python

This week in PL&D we started looking at decision structures; if, else if (elif) and else as well as case structures. We were only given two exercises and I wanted to use both structures so when I got to the second one and started writing the python it occurred to me that I had never used a python case statement. I looked it up and sure enough they don’t exist. I found that there are numerous workarounds but they tend to be oriented towards testing against a specific value or a string, what the exercise called for was testing a value against a range. The most common structure other than simply using if elif else was to put your values into a dictionary. But how to do this with virtually infinite floating point ranges? Than it hit me, use > <= statements as dictionary keys and then simply ask for the ‘True’ value from the dictionary.

# Determine the shipping rate
def getRate(weight) :
        case = {`weight <= 2` :1.1,
        `weight > 2 and weight <= 6` :2.2,
        `weight > 6 and weight <= 10` :3.7,
        `weight > 10` :3.8};
        return case['True']

2 thoughts on “switch case in python

  1. Thanks for that – it’s an interesting approach! It’s just got me thinking that I’ve never really missed having a case statement in Python.. something I always used in C# and Java.

    Have you seen bisect at all? I only just stumbled on this myself.
    Given a sorted set of interval points, and a value, it tells you where in the list the value would fit (0=before 1st element, 1=between 1st and second and so on). You can then use this to look up a list.

    This code does the same thing using bisect.

    import bisect


    print rates[bisect.bisect_left(intervals,weight)]

    1. Actually, no I hadn’t. Thats pretty neat and much more efficient then the ‘case’ dictionary I used. I haven’t had much of a chance to really use python in a while, mostly just playing around at pythonchallenge.com in my spare time and now it is being used in my programming logic class. It is a great language to explore though, lots of libraries and plentiful documentation.

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