What is the alternative of switch statement in Python?

In this article, we will discuss about the alternatives of switch statement in Python.

Table Of Contents

Introduction

In other programming languages, like C++ and Java, we have a switch-case, through which we can execute certain statements in any given condition.

Python Programming language lacks this feature. But we can implement this by using some existing Python functionalities. Although, from python version 3.10 onwards, we have a switch statement (match case) in python. First have a glance on how new Python Switch Case statement works, then we will dive in to our question, what is the alternative for switch statement in Python?

New Switch Statement with match and case keywords in Python

After version 3.10, Python has finally new switch statement with match and case keywords, called as structural pattern matching. In this kind of structure, we have certain cases. When program runs, it checks for conditions on all the cases, and applies the action on the matching case. If condition of any case is not satisfied, then there is a default case which will be used.

SYNTAX

switch:
    case1:
        action1
    case2:
        action2
    case _:
        default

See the example code below

CODE :

weather = input('Enter a weather name: ')

match weather:
    case "Summer":
        print('Turn on AC')
    case "Winter":
        print("Turn on heater")
    case _:
        print("Can't understand")

OUTPUT :

Enter a weather name: Summer
Turn on AC

In this example, we have a fun program based on switch statement(match) in python, which execute some statements based on user input. Also there is a default option, if the user input doesn’t match any of the cases then statements in the default block will be executed. For example, execute the above code with some other input, so that it goes in the default block. Like this,

Enter a weather name: Sprint
Can't understand

As the given imput didn’t matched any case statement, therefore statements in default block are executed.

Now let’s learn about some alternatives for Switch Statement in Python.

Alternative of Switch Statement in Python: If-Else-Elif

As we all know about If-Else-elif conditionals in Python Programming Language. In almost in every programming language, we use these conditionals. We can use these conditionals as an alternative for Switch Statement in Python.

SYNTAX

if condition:
    action
elif condition:
    action
else:
    default

Now see the example code below

CODE :

weather = input('Enter a weather name: ')

if weather == "Summer":
    print('Turn on AC')
elif weather == 'Winter':
    print('Turn on Heater')
else:
    print("Can't understand")

OUTPUT :

Enter a weather name: Winter
Turn on Heater

In the above example, we have used if-else-elif as an alternative for switch statement in Python. Here we have conditional statements in if-elif block with indentation and else block contains our default value. This can be always used as an alternative for almost all the functionalities of a Switch Case statement.

Alternative of Switch Statement in Python: Using dictionary

Next, we can use dictionary class, as an alternative for switch statement in Python. A Dictionary in Python, holds the data in key:value pairs, inside the curly braces separated by a comma. Here we will use this key:value pairs as our switch case statements.

See the example code below

CODE :

# initialized a Dictionary
weatherActions = {  'Summer': 'Turn on AC',
                    'Winter': 'Turn on Heater'}

# taking user input
weather = input('Enter a weather name: ')

# Checking input value against user input,
# second argument works as Default.
result = weatherActions.get(str(weather), 'Cant Understand')

print(result)

OUTPUT :

Enter a weather name: Winter
Turn on Heater

In the above example, we have used a Dictionary as an alternative for the switch statement in Python. Here, we have cases in the form of key and get() method of dict has been used with user input as an argument. This checks the keys for user input, and returns the value. Also there is a second argument in the dict.get() method, which works as a default case of switch. If nothing matches with the given input, then the second argument will be returned.

Summary

So, today we learned about some alternatives for switch statement in Python. Also we learned about the match statement in Python, which is similar to switch-case statement in other programming language. But this match statement was introduced in python version 3.10. Also we learned about how we can use dict and if-elif-else as an alternatives to switch statement in Python.

You can always use both the methods but easy to write and understand is the if-else-elif method, which is mostly identical to the switch-case statement, and flow of the program also looks similar. Bonus point is, we can use else block as the default method in if-elif-else block.

If you want to use new match case statement, you need python version 3.10 and above. To check python version installed type python --version in the command prompt.

Make sure to read this article and write example codes to have a better understanding. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top