Guide of Switch Case Statement in Python – Python, in fact, supports the switch statements. To implement a switch case in Python, we have to add a colon followed by the block of code which is to be run if the condition is matched.
What is a Switch statement?
In computer programming terms, “switch case” is a kind of conditional statement that allows the value of an expression to change how subsequent lines of code execute based on preset conditions. This enables programmers to create unique pathways through their code. Both switch, case, and IF statements are embedded in several different programming languages and allow basic branching commands to be executed once certain conditions are met.
Need of Switch Case Statement
When programming, there are times when we need to execute a certain block of code depending on some other situation. If the given situation does not satisfy, the code block is skip and does not run. Applying this type of format for the purpose of making automatic decisions about which code to run is call as branching. The length and complexity of the code can be reduce simply by automating those kinds of decisions.
Switch Statement in C++/Java
The syntax for switch case statement in C++ is as given:
switch(expression) { case constant-expression : statement(s); break; //optional case constant-expression : statement(s); break; //optional // multiple number of case statement is allowed default : //Optional statement(s); }
Explanation of code:
- Expression: It should be an integral type or enumerated type.
- Constant expression: If you are trying to compare a variable to a different variable, make sure that both of those variables have the same data type.
- Break: The break statement is used to terminate the switch case statement. If the value matches the specified variable, it exits immediately. Otherwise, the flow of execution continues in a linear fashion towards the next line of code after the switch statement.
- Default: The default case is used in a switch statement to handle the situation when no further cases are able to be executed. Declaring the default case is optional, but recommended to help error control and prevent bugs from slipping through in more advanced versions of your code.
Example:
#include
using namespace std;
int main () {
int markz = '90';
switch(grade) {
case '5' :
cout << "You scored 5 markz " << endl;
break;
case '7' :
cout << "You scored 7 markz " << endl;
break;
case 'D' :
cout << "You scored 10 markz " << endl;
break;
default :
cout << "You scored 0 markz " << endl;
}
cout << "Your marks is " << markz << endl;
return 0;
}
Output:
You scored 90 markz Your markz are 90
How to implement Switch Case in Python?
There is a three-way you can apply on python
- If-elif-else
- Dictionary Mapping
- Using classes
Method 01: If-elif-else
Python Switch Syntax with If-elif-else:
if (condition): statement elif (condition): statement . . else: statement
Example:
# if-elif statement example
fruit = 'Banana'
if fruit == 'Mango':
print("letter is Mango")
elif fruit == "Grapes":
print("letter is Grapes")
elif fruit == "Banana":
print("fruit is Banana")
else:
print("fruit isn't Banana, Mango or Grapes")
Output:
fruit is Banana
Method 02: Dictionary Mapping
Example:
# Implement Python Switch Case Statement using Dictionary
def monday():
return "monday"
def tuesday():
return "tuesday"
def wednesday():
return "wednesday"
def thursday():
return "thursday"
def friday():
return "friday"
def saturday():
return "saturday"
def sunday():
return "sunday"
def default():
return "Incorrect day"
switcher = {
1: monday,
2: tuesday,
3: wednesday,
4: thursday,
5: friday,
6: saturday,
7: sunday
}
def switch(dayOfWeek):
return switcher.get(dayOfWeek, default)()
print(switch(3))
print(switch(5))
Output:
wednesday friday
Method 03: Using classes
Example:
class PythonSwitch:
def day(self, dayOfWeek):
default = "Incorrect day"
return getattr(self, 'case_' + str(dayOfWeek), lambda: default)()
def case_1(self):
return "monday"
def case_2(self):
return "tuesday"
def case_3(self):
return "wednesday"
def case_4(self):
return "thursday"
def case_5(self):
return "friday"
def case_7(self):
return "saturday"
def case_6(self):
return "sunday"
my_switch = PythonSwitch()
print (my_switch.day(1))
print (my_switch.day(3))
Output:
monday wednesday
That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn
Suggested Articles: