Why Having a Switch/Case in Python Would Be Useful
In this lesson, you’ll see why having switch/case in Python would be useful. Python does not have a switch/case statement and because of this, many Python developers useif
statements to decide on what action to take based on a condition:
if cond == 'cond_a':
handle_a()
elif cond == 'cond_b':
handle_b()
else:
handle_default
This lesson will go over some of the problems of using this approach.
00:00
I want to talk about a really cool Python trick, and that is a way to emulate switch/case statements in Python. What I frequently see in Python code is that people end up with these relatively long if
statements—these kind of chained if
statements to decide on what action to take based on a condition in their code. To give you an example, let’s say we had this if
statement where we had a condition and we wanted to compare it to a certain value and then, okay, if we get A, I want to call handle_a()
, and if we get
00:38
a condition B, then we’re going to call handle_b()
, and if we get none of these, then we’re going to call handle_default()
. Right?
00:49 And you can imagine that this would go on for much longer, and this would get kind of cumbersome, right?
00:57 It’s a lot of typing, and the reason for that is Python doesn’t really have a switch/case statement which we could use to condense this a bit and make it more terse and easier to read.
01:12 So, there is actually a way to emulate that switch/case behavior in Python, and I want to show you how to do that.
Become a Member to join the conversation.