# Use Python to do Switch Case

The switch statement can be very useful sometimes, and it is pretty easy to handle multiple conditions instead of writing a lot of if else. Here is the example of writing switch statement in most of languages:

But the problem is, Python doesn't have switch statement. There's a proposal for that; however the status of this proposal is rejected. The explanation from python.org is you can simply use if...elif...else to do the same thing, but I guess the main reason is because they don't have consensus about adding switch into Python(yet). You can check Python FAQ or PEP 275 to get more detail about the switch statement in Python.

Of course we know that you can always use if...elif...else to do the exactly the same thing, but if there are too many elif, that might cause some problem to maintain or understand the code.

They might not agree with me, but I do have a suck example to show the worst case of using if...elif...else. This is a part of code of parsing excel data.

Using if...elif...else is definitely simple enough to write, but when you go back to check this long statement again, you might need couple minutes to understand what's going on in here. Maybe it's just me, but I personally don't like to see a lot of if in the code.

I know that we don't have switch statement in Python, but you can still use dictionary to make it look better than if...elif...else. After I modify the whole if...elif...else statement, it looks much better to me.

This is a complex example of doing switch in Python, which might be a little bit hard to understand. Let's start with some simple examples.

So, what if I want to provide a default value for the gender information? You can use the dictionary's .get() method to provide the default value for that.

Sometimes, we need to have something more than just returning string, so let's see how to pass paramter into the dictionary.

What if I also want to provide default case to avoid the KeyError issue in this situation?

If you need more functionalities, you can call function in lambda, or just call the function directly.

Like we mentioned before, you can always use if...elif...else to do the same thing, but here's another way to make your code easier to understand and maintain.