visit
switch (variable/expression) {
case value1:
// statements of case1
break;
case value2:
// statements of case2
break;
.. .. ...
.. .. ...
default:
// default statements
}
Yeah, I know what you might be thinking by now. What's the big deal you could just use the
if-elif-else
statement instead?Sure, you could but when dealing with multiple conditions the switch statement is more convenient and feels a lot cleaner.So, now to the main part, How to get the switch statement in Python ?Well to be honest, there is no switch statement in Python. But wait, dont click the close button just yet. I have a workaround to this problem.Suppose you want to write a function
month_tracker()
, that takes in the current month as an integer and returns the name of the month.If you use
if-elif-else
statement this is how your code would look like;def month_tracker(month):
if month == 1:
month_name = 'January'
elif month == 2:
month_name = 'February'
elif month == 3:
month_name = 'March'
elif month == 4:
month_name = 'April'
elif month == 5:
month_name = 'May'
elif month == 6:
month_name = 'June'
elif month == 7:
month_name = 'July'
elif month == 8:
month_name = 'August'
elif month == 9:
month_name = 'September'
elif month == 10:
month_name = 'October'
elif month == 11:
month_name = 'November'
elif month == 12:
month_name = 'December'
else :
month_name = 'January'
return month_name
def month_tracker(month):
switch = {
1 : 'January',
2 : 'February',
3 :'March',
4 :'April',
5 :'May',
6 :'June',
7 :'July',
8 :'August',
9 :'September',
10 :'October',
11 :'November',
12 :'December',
}
return switch.get(month,1)