Match
The match statement can be used to combine several elif statements. This is used to simplify code.
Here's an example:
fruit = "apple" if fruit == "apple": print("A for apple") elif fruit == "berry": print("B for berry") elif fruit == "cherry": print("C for cherry") else: print("I don't know that fruit")
Output:
A for apple
Match
Again, just like the if/elsif/else statement only one of the blocks is going to execute.
match.py
fruit = "berry" # a better way match fruit: case "apple": print("A for apple") case "berry": print("B for berry") case "cherry": print("C for cherry") case default: print("I don't know that fruit")
Output:
B for berry
Links
Exercises (5 mins)
-
Complete the following program so that it matches the output.
# Enter a month number (1-12) month = input("Enter a month number (1-12):") # Use the match statement for the rest of the months match month: case "1": print("January")
Output:
Enter a month number (1-12): 1 January Enter a month number (1-12): 12 December Enter a month number (1-12): 14 I don't know that month