Python switch case

Learn how to write switch case logic in Python using match case, if-elif statements, and dictionary mapping. See Python switch statement examples, default cases, multiple cases, and when to use each approach.

Published

Updated

Read time 7 min read

Reviewed byDeepak Prasad

Python switch case

Python does not use a traditional switch / case keyword like C, Java, or JavaScript. In Python 3.10 and newer, you can write switch-like logic with match case. For Python 3.9 and older, or for simple value-to-result lookups, use if-elif-else or dictionary mapping.

Use match case in Python 3.10+ when you want clear multi-way branching. Use a dictionary when you only need a lookup table. Use if-elif-else for ranges, comparisons, and complex boolean conditions.

Python's official tutorial describes match as superficially similar to switch, but more powerful because it also supports structural pattern matching. For basic switch-style value matching, match case is the modern answer.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


Python switch case quick reference

Task Best option
Python 3.10+ switch-like syntax match case
Python 3.9 or older if-elif-else or dictionary mapping
Match one value from many choices match case
Return value from fixed keys dictionary mapping
Run functions based on command dictionary dispatch
Handle default case case _ or dict.get(default)
Match multiple values in one case case "start" | "run"
Match structured data match case with patterns
Simple conditions with ranges if-elif-else
Complex boolean conditions if-elif-else

Does Python have switch case?

  • Python does not have a switch keyword.
  • Python 3.10+ has match case for switch-like control flow.
  • match case matches the first fitting pattern and stops—no break needed.
  • On older Python, use if-elif-else or a dictionary.

If you come from C, Java, or PHP, think of match as the modern Python switch—not identical, but the closest built-in syntax for “pick one branch from many values.”


Python match case syntax

Basic shape:

text
match expression:
    case pattern1:
        ...
    case pattern2:
        ...
    case _:
        ...

Rules that matter for switch-style use:

  • match expression: — value to compare or destructure.
  • case pattern: — branch when the pattern matches.
  • case _: — default branch when nothing else matches.
  • Only the first matching case runs.
  • No break is required—Python does not fall through to the next case by default.

Simple Python switch case example using match case

Map a day number to a day name:

python
def day_name(day):
    match day:
        case 1:
            return "Monday"
        case 2:
            return "Tuesday"
        case 3:
            return "Wednesday"
        case _:
            return "Invalid day"

print(day_name(1))
print(day_name(2))
print(day_name(99))
Output

The output is Monday, Tuesday, and Invalid day.

Menu-style status messages work the same way:

python
def status_message(code):
    match code:
        case 200:
            return "OK"
        case 404:
            return "Not found"
        case 500:
            return "Server error"
        case _:
            return "Unknown status"

print(status_message(200))
print(status_message(418))
Output

You get OK and Unknown status.


Default case in Python switch case

Use case _: as the default branch. Place it last so specific cases are checked first:

python
def menu_action(choice):
    match choice:
        case "add":
            return "Adding item"
        case "delete":
            return "Deleting item"
        case "exit":
            return "Goodbye"
        case _:
            return "Unknown command"

print(menu_action("add"))
print(menu_action("help"))
Output

The unknown command returns "Unknown command".


Match multiple cases in one Python case statement

Combine alternatives with |:

python
def handle_command(cmd):
    match cmd:
        case "start" | "run" | "go":
            return "Starting"
        case "stop" | "exit" | "quit":
            return "Stopping"
        case _:
            return "Unknown command"

print(handle_command("run"))
print(handle_command("quit"))
print(handle_command("pause"))
Output

run and quit match grouped cases; pause hits the default.


Python switch case with if condition / guard

Add an if guard after a pattern when equality alone is not enough:

python
def ticket_price(age):
    match age:
        case n if n < 0:
            return "Invalid age"
        case n if n < 18:
            return "Child ticket"
        case n if n >= 65:
            return "Senior ticket"
        case _:
            return "Adult ticket"

print(ticket_price(10))
print(ticket_price(30))
print(ticket_price(70))
Output

Guards are useful for ranges and validation. For many range checks with no pattern matching, plain if-elif-else may still read more clearly—see if-else in Python.


Python switch case with strings

String commands are a common switch-style use case:

python
def process_command(command):
    match command.lower():
        case "add":
            return "Record added"
        case "update":
            return "Record updated"
        case "delete":
            return "Record deleted"
        case "exit":
            return "Exiting"
        case _:
            return f"Unknown command: {command}"

print(process_command("add"))
print(process_command("REMOVE"))
Output

Matching on command.lower() keeps "ADD" and "add" consistent.


Python switch case with functions

match case keeps command flow readable when each branch runs different logic:

python
def add(): return "add"
def delete(): return "delete"

def route(action):
    match action:
        case "add":
            return add()
        case "delete":
            return delete()
        case _:
            return "unsupported"

print(route("add"))
print(route("archive"))
Output

For simple command → function routing, dictionary dispatch is often cleaner—see the next section and Python functions for defining the callables you map to.


Python switch case using dictionary mapping

A dictionary is ideal when each key maps to a fixed result and you do not need match syntax:

python
DAYS = {
    1: "Monday",
    2: "Tuesday",
    3: "Wednesday",
    4: "Thursday",
    5: "Friday",
    6: "Saturday",
    7: "Sunday",
}

print(DAYS.get(4, "Invalid day"))
print(DAYS.get(10, "Invalid day"))
Output

Use dict.get(key, default) for a default when the key is missing—similar to default in other languages.

Status codes and roles fit the same pattern:

python
MESSAGES = {
    200: "OK",
    404: "Not found",
    500: "Server error",
}

print(MESSAGES.get(404, "Unknown status"))
Output

This works on all Python versions and stays very readable for lookup tables.


Python dictionary dispatch for switch-like functions

Map commands directly to functions:

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

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

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

def divide(a, b):
    return a / b

def unknown(a, b):
    return "Invalid operation"

OPERATIONS = {
    "+": add,
    "-": subtract,
    "*": multiply,
    "/": divide,
}

def calculate(symbol, a, b):
    operation = OPERATIONS.get(symbol, unknown)
    return operation(a, b)

print(calculate("+", 8, 4))
print(calculate("/", 8, 4))
print(calculate("%", 8, 4))
Output

You get 12, 2.0, and "Invalid operation". This pattern suits calculators, CLI commands, and menu actions without a large if-elif chain.


Python switch case using if-elif-else

if-elif-else works on every Python version and fits ranges and complex conditions:

python
def grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

print(grade(92))
print(grade(55))
Output

Boolean logic also belongs here:

python
def access(role, is_active):
    if role == "admin" and is_active:
        return "full access"
    elif role == "user" and is_active:
        return "limited access"
    else:
        return "no access"

print(access("admin", True))
print(access("user", False))
Output

For two-value selection in one expression, see the Python ternary operator.


match case vs if-elif vs dictionary mapping

Approach Best for Python version
match case Switch-like value matching and pattern matching Python 3.10+
if-elif-else Ranges, comparisons, complex boolean conditions All versions
Dictionary mapping Fixed value-to-result lookup All versions
Dictionary dispatch Command-to-function routing All versions

Recommendation: use match case for modern switch-like code on Python 3.10+. Use dictionary mapping for simple lookup tables. Use if-elif-else when conditions are not simple equality checks.


Python match case vs traditional switch case

Feature Traditional switch Python match case
Keyword switch / case match / case
Default branch default case _
break required Often yes No
Fallthrough Common in some languages No normal fallthrough
Match simple values Yes Yes
Match data structures Usually no Yes
Python version Not Python syntax Python 3.10+

Python 3.9 and older switch case alternatives

match case is unavailable before Python 3.10. On older interpreters:

  • Use if-elif-else for branching logic.
  • Use dictionary mapping for key → value tables.
  • Use dictionary dispatch to map commands to functions.

Class/getattr tricks can mimic switch behavior, but dictionaries or if-elif are clearer for most teams today—especially now that match case exists on supported Python versions.


When should you use match case?

Use match case when:

  • You run Python 3.10 or newer.
  • You match one value against many cases.
  • You want a clear default with case _.
  • You need to match structured data (tuples, objects, etc.).

Avoid match case when:

  • A simple dict.get() lookup is enough.
  • You mainly need range checks (score >= 90).
  • You must support Python 3.9 or older.
  • A plain if-elif block is easier to read.

Summary

Python has no switch keyword, but Python 3.10+ supports match case for switch-like logic. Use case _ for the default branch. Use dictionary mapping for simple key-value lookups, dictionary dispatch for command-to-function routing, and if-elif-else for ranges and complex conditions on any Python version.

Useful references


Frequently Asked Questions

1. Does Python have a switch case statement?

Python has no switch keyword like C or Java. Python 3.10+ adds match case for switch-like logic. On older versions, use if-elif-else or dictionary mapping.

2. What is the Python equivalent of switch case?

Use match case in Python 3.10 and newer. For simple value lookups on any version, use a dictionary with dict.get(key, default).

3. How do you write a default case in Python match case?

Use case _ at the end. It runs when no other pattern matches, similar to default in other languages.

4. Do you need break in Python match case?

No. Only the first matching case runs. Python match case does not fall through like C-style switch.

5. When should I use dictionary mapping instead of match case?

Use a dictionary when you only need fixed key-to-value lookup with no extra logic. It works on all Python versions and is often shorter than match for simple tables.

6. Does match case work on Python 3.9?

No. match case was added in Python 3.10. On Python 3.9 and older, use if-elif-else or dictionary dispatch.
Bashir Alam

Data Analyst and Machine Learning Engineer

Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and …