Search code snippets, questions, articles...

Python Switch Case: A Comprehensive Guide with Examples

If you're looking for a comprehensive guide on how to use switch case in Python, look no further! This guide will cover everything from the basics of switch case to more advanced concepts. We'll also provide plenty of examples to help you along the way.
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

For Python version above - 3.10 use match case

If you are using Python version 3.10 or above, then use the match case statement in your code that will work precisely like a switch case statement in programming.

Understand it using the below code example:

def num_to_word(num):
    match num:
        case 1:
            return "one"
        case 2:
            return "two"
        case 3:
            return "three"
        case 4:
            return "four"
        case default:
            return "not_found"

result = num_to_word(3)

print("Result is: ", result)

Output

Result is:  three

The python code example defines a function called num_to_word() that takes an input of num. The function then uses a match statement to check the value of num.

If the value of num is equal to 1, 2, 3, or 4, the function will return the string "one", "two", "three", or "four" respectively. If the value of num is anything else, the function will return the string "not_found".

The code then calls the num_to_word() function with input 3 and assigns the return value to the variable result. Finally, the code prints the string "Result is: " followed by the value of the result.

For versions, less than 3.10 - use the if-else statement

Until Python version 3.10, there is no version of Python that has a Switch case statement like other programming languages. But we can use the if-else statement as its replacement. So if you are using the Python version below 3.10 then you can use if-else to implement switch case-like functionality.

Below is the example to implement switch case like scenario using if-else statement.

def num_to_word(num):
    if num == 1:
        return "one"
    elif num == 2:
        return "two"
    elif num == 3:
        return "three"
    elif num == 4:
        return "four"
    else:
        return "nothing"

result = num_to_word(3)

print("Result is: ", result)

Output

Result is:  three
Was this helpful?
0 Comments