The switch case is a decision-making statement that enables switching on a single variable where that variable may have one or multiple possible values.
The switch statement is available in many programming languages including Java, PHP, JavaScript etc.
The question is what is the alternative? As such, the scenarios will come where you need the switch case usage as doing programming in Python.
The official site suggests using the if…elif…elif..else statements for the limited number of possibilities (say up to 12 or so). However, for a very large number of possibilities, you may create a dictionary.
In that case, the dictionary will map the case values to functions call. I will show the running example with code in the coming section.
First alternative – using the dictionary
- As mentioned in the official documentation, you should use the dictionary mapping case values to function call.
- This is demonstrated in the demo below.
- The scenario is to get the current month from the system and display a respective message on the screen.
- As there are only twelve possibilities, so 12 “cases” are created i.e. one function for each month.
- The current month value is obtained by using the datetime module and this is how the dictionary is mapped with case values.
Python program:
import datetime curr_Month = datetime.date.today().strftime("%B") #Functionas are created for each case def Jan (): print("January - Starting new Year") def Feb (): print("February - The Second Month") def Mar (): print("March - The Third Month") def Apr (): print("April - The Fourth Month") def May (): print("May - The Fifth Month") def Jun (): print("June - The Sixth Month") def Jul (): print("July - The Seventh Month") def Aug (): print("August - The Eighth Month") def Sep (): print("September - The Ninth Month") def Oct (): print("October - The Tenth Month") def Nov (): print("November - The Eleventh Month") def Dec (): print("December - The End of Year") #Dictionary containing all possible values Month_Dict = { "January": Jan, "February": Feb, "March": Mar, "April": Apr, "May": May, "June": Jun, "July": Jul, "August": Aug, "September": Sep, "October": Oct, "November": Nov, "December": Dec } #The switch alternative Month_Dict.get(curr_Month)()
Sample Output:
So, the curr_Month is assigned the system value for Month by using datetime.date.today().strftime(“%B”). This is passed to the dictionary get method that is mapped to a function call.
What if a case value is non-existent – the default statement?
In above example, we used the Month value that we obtained using the time module. So, there was no possibility that a non-existent case happen.
What if a value does not exist?
Suppose, we set the value for curr_Month variable a non-month, see what will happen to the above example:
curr_Month = ‘No Month’
As you execute the above example with this value, this will be the output:
So, an error occurs. How to avoid this?
Using the default “case”
To avoid the error, you may create a default function that acts as an alternative to the “default case” in the switch context.
So if none of the cases matches the provided value, the default function should execute.
This is demonstrated in the example below.
- A user is asked to enter a number from 1 to 7 by using the input function.
- The 1 represents Monday, 2 for Tuesday, and so on. For any other entry, the default case will execute.
- See the code and output:
#A Demo of switch case with default case day_num = input("Enter a day number from 1-7? ") #Functionas are created for each day with default case def Mon (): print("Its Monday") def Tue (): print("Its Tuesday") def Wed (): print("Its Wednesday") def Thu (): print("Its Thursday") def Fri (): print("Its Friday") def Sat (): print("Its Saturday") def Sun (): print("Hurray, Its Sunday!") def Default_case (): print("Wrong entry! The number must be 1-7") #Dictionary containing all possible 'cases' Week_Dict = { "1": Mon, "2": Tue, "3": Wed, "4": Thu, "5": Fri, "6": Sat, "7": Sun } #The switch alternative Week_Dict.get(day_num,Default_case)()
Sample Output:s
In the output figure, you can see the last entry is 11 and it executed the default case rather than producing an error.
Switch alternative 2 – using if..elif..elif..else statement
As per official recommendation, for the small number of possibilities, you may use the if..elif, elif…else statements.
See the above Week example by using this approach:
w = int(input("Enter a day number from 1-7? ")) if (w == 7): print("Its Sunday."); elif (w == 1): print("Monday is the the first working day!"); elif (w == 2): print("Tuesday!!!"); elif (w == 3): print("Wednesday...Getting closer!"); elif (w == 4): print("and mmore...its Thursday!"); elif (w == 5): print("Friday...Hurray! so close!"); elif (w == 6): print("Yay, the Weekend started, as its Sat!"); else: print("Wrong entry! The number must be 1-7");
For more on if..elif and else statements, follow the link.