Switch Case in Python

Imagine, the switchboard at home every switch is dedicated to some device. When you on/off the switch only that device responds to the signals.


2 min read


In python, there is no switch case, unlike other programming languages. So the question comes how do we write a switch case in python?

Basically, there are two ways in which you can try to implement the switch case logic in python where you intend to execute certain statements when a particular case is matched.

  • Using if-elif-else block
  • Using python dictionary

In this article, we will check both the ways by writing a function that performs arithmetic operations on the numbers passed to the function. The function would take the two numbers and operation as function arguments and return the result based on the operation passed to the function.

Let's begin

Function to write switch-case using if-elif-else

The if-elif-else is used in python to write conditional statements as in other programming languages. You can write a switch case by checking every operation passed to function and based on the condition you can return the result.

This is how it is done,

def switch_case_function(x, y, op):
    if op == "add":
        return x + y
    elif op == "sub":
        return x - y
    elif op == "div":
        return x/y
    elif op == "mul":
        return x * y
        return "no valid operation"


Function to write switch-case using python dictionary

Python dictionaries are used to store data in key-value pairs. The key of the dictionary must be an immutable datatype. The dictionary itself is mutable and it does not allow duplicate keys.

You can create a python dictionary in the following ways:

# creating an empty dictionary in python
mapping = {}        
mapping = dict() 

# creating a dictionary with key-value pairs
mapping = {"language" : "python", "creator" : "guido van rossum"}
mapping = dict(language="python", creator="guido van rossum")

The main thing to notice here is while you use dict() and pass the key-value pair, you can directly pass the key as the variable name instead of passing it as strings, as when creating a dictionary using curly braces.

To get a value from the dictionary you can use the built-in get() method on the dictionary object. It returns the value of the key if a key exists else returns the default.

def switch_case_function(x,y,op):
    operation_mapping = dict(add=x+y, sub=x-y, mul=x*y, div=x/y)
    # returns no valid operation if key does not exists.
    return operation_mapping.get(op, "no valid operation") 



Python does not have switch cases unlike other programming languages but you can implement the logic using the two methods shown above. The code is more readable when you write using python dictionaries. You can make your own choice.

Thanks for reading ๐Ÿ™‡๐Ÿปโ€โ™‚๏ธ