how.wtf

Python switch statement example

· Thomas Taylor

Python 3.10 added support for the switch keyword.

Implement switch statements in Python

The basic syntax for a switch statement is:

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

A direct example:

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

Output:

1small pizza

In Python, break statements are not required.

#Python  

Reply to this post by email ↪