Switch Case in Python and Switch Statement Example

Switch Case in Python— A switch case statement is a control structure in programming which allows programmers to control the flow of their programs using the value of a variable or an expression. Most programming languages like C/C++, Java, or JavaScript have built-in switch structures which programmers can use for decision-making in a software solution.

Syntax of Switch Statement

The general syntax of a switch statement is as follows:

switch(expression){
case value1:
       # statement to be executed
case value2:
      # statement to be executed
case valueN:
      # statement to be executed
default:
     # statement to be executed if no other case is met
}

How Does Switch Statement Work?

Switch statements work by matching the expression with a specific case. The code in that case block is executed if a case is matched. If no case is matched, the code in the default block is executed instead.

if-else vs. Switch Case Statement

Switch statements are generally used when programmers need to control the program flow based on a single value of an expression or a variable. In addition, the if-else statement is generally used when programmers need to control the program flow of their programs based on the range of values a variable or expression can take.

Switch Case in Python

Despite the apparent usefulness of the switch case statements, Python does not offer any built-in implementation of switch cases. However, there are multiple ways that programmers can achieve this functionality by using switch statements in their programs.

Implementation of Switch Case in Python

Some popular methods to implement switch cases in Python are:

  1. Using if...elif...else statements
  2. Using match...case keywords

Using if...else For Switch Case in Python Implementation

Programmers can use the elif keyword in addition to if and else keywords to implement the functionality of switch cases in their programs. If the same switch case is repeated multiple times in the program, a function can also be created to make the code more readable and reusable.

The following example illustrates how a function can be created to implement the functionality of a switch case in a Python program, which replicates the functioning of a simple calculator.

# created two float type operands
operand1 = float(input("Enter the first number : "))
operand2 = float(input("Enter the second number : "))
# creating variable for keep operator
operator = input("Enter the operation (+, -, *, /) : ")
result = 0.0
# if..else statements 
if operator == "+":
            result = operand1 + operand2
elif operator == "-":
            result = operand1 - operand2
elif operator == "*":
            result = operand1 * operand2
elif operator == "/":
            result = operand1 / operand2
else:
            print("Incorrect Operator Entered")
# printing results on console calculated as above 
print(f'{operand1} {operator} {operand2} = {result}')

Output

 switch case in python
if else for switch case in Python
  • Line#2,3: Using the input function to invoke user to enter both operands. then float() function to cast the entered numbers in decimal format.
  • Line#5: Using input() function to let the user enter the operator.
  • Line#8-15: Using nested if...else keywords to check the operator’s value and simulate the case keyword’s functionality in switch statements.
  • Line#16: In this line, else keyword acts as the default block of the switch statement.
  • Line#19: Prints the calculated result.

Using match...case For Switch Implementation

Programmers using Python 3.10 or above can use Match and Case keywords to implement switch case functionality in their programs. Using match...case is comparatively easier than using if...else to implement a switch case in Python because the syntax of match...case is similar to that of a switch case in other programming languages.

Syntax for using match...case

# Syntax
match variable/expression:
   case value1:
     # action-1
   case value2:
     # action-2
    case value3:
     # action-3
    case _:
     # action-default

Implementation of the calculator in the above example using the Match and Case keyword is as follows:

# created two float type operands
operand1 = float(input("Enter the first number : "))
operand2 = float(input("Enter the second number : "))
# creating variable for keep operator
operator = input("Enter the operation (+, -, *, /) : ")
result = 0.0
# using match...case operator
match operator:
            case "+":
                        result = operand1 + operand2
            case "-":
                        result = operand1 - operand2
            case "*":
                        result = operand1 * operand2
            case "/":
                        result = operand1 / operand2
            case _:
                        print("Incorrect Operator Entered")
# printing results on console
print(f'{operand1} {operator} {operand2} = {result}')
  • Line#2,3: The input() function invokes the user to enter both operands. Then float() function to cast the entered numbers in decimal format.
  • Line#5: Uses the input function to let the user enter the operator.
  • Line#7: Begins the Switch statement of the program.
  • Line#8-15: Using the case keywords to check the value of the operator & simulate the functionality of the case keyword in switch statements.
  • Line#16: case _: acts as the default block of the switch statement.
  • Line#19: Prints the calculated result.

Stay in the Loop

Get the daily email from Algoideas that makes reading the news actually enjoyable. Join our mailing list to stay in the loop to stay informed, for free.

Latest stories

- Advertisement -

You might also like...