Switch-case statement in Python
Tags: coding, python, beginners, programming
Published: 2022-09-29 02:01:45

---
title: Switch-case statement in Python
published: true
date: 2020-12-19 20:21:08 UTC
tags: coding,python,beginner,programming
canonical_url: 
---

![](https://cdn-images-1.medium.com/max/1024/0*JV4ilI-ryJaxuTgc)
_Photo by Maxwell Nelson on Unsplash_

One of the most shocking things that I found during my first months using Python is, **the switch-case statement** does not exist. Previously, I had only worked with languages like C or Java. Both of them provide you with a switch statement to avoid an if-else if hell.

Of course, this has an explanation; you can read the full discussion [here](https://www.python.org/dev/peps/pep-3103/) and see why Guido Van Rossum himself rejected it.

In this post, I will show you two quick workarounds to implement a switch-case like functionality.

Let’s work with a simple example. You have to create a script to simulate a calculator, think about the basic operations a calculator can perform; add, subtract, divide, and multiply.

```
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def divide(a, b):
    if b == 0: # To catch division by zero errors
        return 'Error dividing by zero' 
    return a // b # To return int instead of float

def multiply(a, b):
    return a * b
```

The operation functions are ready; let’s add a ‘main’ menu to put everything together.

```
def calculator(operation_option, a, b):
    int_a, int_b = int(a), int(b) # To cast string values to ints
    
    if operation_option == 'add':
        result = add(int_a, int_b)

    elif operation_option == 'subtract':
        result = subtract(int_a, int_b)

    elif operation_option == 'divide':
        result = divide(int_a, int_b)

    elif operation_option == 'multiply':
        result = multiply(int_a, int_b)

    else: # Default case
        result = f'Invalid operation {operation_option}'

    return result


if __name__ == ' __main__':
    operation = input('Type operation name: ').lower()
    # lower() will help to manage everything as lowercase

    num_a = input('Type first number: ')
    num_b = input('Type second number: ')

    # since num_a and num_b are mean to be integers
    # lower is unnecessary

    result = calculator(operation, num_a, num_b)

    print(result)
```

As you can see, if the user wants to add, only one comparison happens; on the other hand, if the user wants to multiply, four comparisons are executed.

In this simple example, speed is not important at all, but when it comes to using complex functions where the script execution speed is vital, running too many comparisons might be counterproductive.

### Dictionaries

Python has a built-in map-like object, you know, as many key-value pairs as you want, they can store immutable objects as keys and any object as values.

This workaround implies using a dictionary with string objects as keys and functions as values.

Let’s rewrite the same ‘calculator’ function using a functions dictionary

```
def calculator(operation_option, a, b):
    
    DEFAULT_VALUE = -1
    int_a, int_b = int(a), int(b) # To cast string values to ints

    operations = {
        'add': add(int_a, int_b),
        'subtract': subtract(int_a, int_b),
        'divide': divide(int_a, int_b),
        'multiply': multiply(int_a, int_b)
    }
    result = operations.get(operation_option, DEFAULT_VALUE)

    return result
```

As you can see, this workaround ‘translates’ from string to a function and executes, but **this implementation is wrong**.

This dictionary uses string objects as keys and **integers** as values; this implementation may cause waiting until all the functions finish their execution and fill the dictionary.

The right way then is to make a dictionary with string keys and function values, let’s build that dict.

```
def calculator(operation_option, a, b):
    
    int_a, int_b = int(a), int(b) # To cast string values to ints

    operations = {
        'add': add,
        'subtract': subtract,
        'divide': divide,
        'multiply': multiply
    }
    operation_function = operations.get(operation_option, None)
    # operation_function now points to a function object
 
    if operation_function is None:
        # If the operation does not exist
        return f'Invalid operation {operation_option}'

    # Invoke the function with parameters
    result = operation_function(int_a, int_b)
    
    return result
```

Done! This will make your function dispatch easier and faster, with this last implementation you won’t wait until all the if conditionals ends or until all the functions execute to fill your dictionary option.

Thanks for reading. Every feedback, comment, or sharing is highly appreciated!