— Python, Conditional Statements, Code Logic — 1 min read
Unlike many other programming languages, Python doesn't have a built-in switch
statement. This might seem surprising, but it's a deliberate design choice to promote code readability and flexibility. However, this doesn't mean you're without options.
The most straightforward way to mimic a switch
statement is using a series of if
, elif
, and else
statements. While this approach works, it can become cumbersome for multiple cases.
1def day_of_week(day):2 if day == "Monday":3 print("It's Monday!")4 elif day == "Tuesday":5 print("It's Tuesday!")6 # ... other days ...7 else:8 print("Invalid day")
Another common method involves using dictionaries to map values to functions or actions. This can be more concise for large numbers of cases.
1def day_of_week(day):2 actions = {3 "Monday": lambda: print("It's Monday!"),4 "Tuesday": lambda: print("It's Tuesday!"),5 # ... other days ...6 }7 action = actions.get(day, lambda: print("Invalid day"))8 action()
The introduction of structural pattern matching in Python 3.10 offers a more elegant solution resembling switch
statements. It's particularly useful for complex value comparisons and destructuring.
1def day_of_week(day):2 match day:3 case "Monday":4 print("It's Monday!")5 case "Tuesday":6 print("It's Tuesday!")7 # ... other cases ...8 case _:9 print("Invalid day")
The _
wildcard matches any value not covered by previous cases, acting as a default.
Key Points to Remember:
if-elif-else
are valid, structural pattern matching often aligns better with Python's philosophy.