Python switch statement example

Python 3.10 added support for the switch keyword.

Implement switch statements in Python

The basic syntax for a switch statement is:

1
2
3
4
5
6
7
match term:
    case pattern1:
        some_action
    case pattern2:
        some_other_action
    case _:
        default_action

A direct example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
pizza_size = 0
match pizza_size:
    case 0:
        print("small pizza")
    case 1:
        print("medium pizza")
    case 2:
        print("large pizza")
    case _:
        print("pizza size is not valid")

Output:

1
small pizza

In Python, break statements are not required.