Replacements for switch statement in Python?

Better Stack Team
Updated on February 3, 2023

In Python, the if-elif-else statement can be used as a replacement for a switch statement. Additionally, the dict.get() method or a dictionary of functions can also be used to achieve a similar effect.

Here are a few examples of using the if-elif-else statement as a replacement for a switch statement in Python:

 
def switch_example(case):
    if case == 'a':
        return 'Case A'
    elif case == 'b':
        return 'Case B'
    elif case == 'c':
        return 'Case C'
    else:
        return 'Other Case'

print(switch_example('a')) # 'Case A'
print(switch_example('b')) # 'Case B'
print(switch_example('c')) # 'Case C'
print(switch_example('d')) # 'Other Case'

Here is an example of using the dict.get() method as a replacement for a switch statement in Python:

 
def switch_example(case):
    options = {
        'a': 'Case A',
        'b': 'Case B',
        'c': 'Case C',
    }
    return options.get(case, 'Other Case')

print(switch_example('a')) # 'Case A'
print(switch_example('b')) # 'Case B'
print(switch_example('c')) # 'Case C'
print(switch_example('d')) # 'Other Case'

And here is an example of using a dictionary of functions as a replacement for a switch statement in Python:

 
def case_a():
    return 'Case A'

def case_b():
    return 'Case B'

def case_c():
    return 'Case C'

def other_case():
    return 'Other Case'

def switch_example(case):
    options = {
        'a': case_a,
        'b': case_b,
        'c': case_c,
    }
    return options.get(case, other_case)()

print(switch_example('a')) # 'Case A'
print(switch_example('b')) # 'Case B'
print(switch_example('c')) # 'Case C'
print(switch_example('d')) # 'Other Case'

All of the above examples show different ways of achieving similar functionality as switch statements in python.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github