Title here
Summary here
Switch statements express conditionals across many branches.
Here’s a basic switch
example translated into Python.
def main():
i = 2
print("Write", i, "as", end=" ")
match i:
case 1:
print("one")
case 2:
print("two")
case 3:
print("three")
if __name__ == "__main__":
main()
You can use vertical bars to separate multiple expressions in the same case
statement. We use the optional default
case in this example as well.
from datetime import datetime
def main():
day_of_week = datetime.now().strftime('%A')
match day_of_week:
case "Saturday" | "Sunday":
print("It's the weekend")
case _:
print("It's a weekday")
if __name__ == "__main__":
main()
match
without an expression is an alternate way to express if/else logic. Here we also show how the case
expressions can be non-constants.
from datetime import datetime
def main():
now = datetime.now().hour
match now:
case h if h < 12:
print("It's before noon")
case _:
print("It's after noon")
if __name__ == "__main__":
main()
A type match
compares types instead of values. You can use this to discover the type of a variable. In this example, the variable t
will have the type corresponding to its clause.
def what_am_i(i):
match i:
case bool(_):
print("I'm a bool")
case int(_):
print("I'm an int")
case _:
print(f"Don't know type {type(i).__name__}")
def main():
what_am_i(True)
what_am_i(1)
what_am_i("hey")
if __name__ == "__main__":
main()
$ python switch_example.py
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type str