Python does not have a built-in switch statement like some other languages (e.g., C, C++, Java, JavaScript). However, Python offers several ways to handle multiple conditions that can serve similar purposes. You can use the match-case statement introduced in Python 3.10 to achieve the functionality of a switch statement.
Python 3.10 introduced the match-case statement, which offers functionality similar to a switch statement in other languages. This new syntax allows for pattern matching and can be more expressive than using other sequence data types, which you will learn in later modules.
value = 2 |
In this example,
- Case 1: If value is 1, it prints "One".
- Case 2: If value is 2, it prints "Two".
- Case 3: If value is 3, it prints "Three".
- Case _: The underscore _ acts as a wildcard or default case, executing if none of the previous cases match.
Explanation of match-case Syntax:
- match Keyword: Starts the pattern matching block, similar to switch.
- case Keyword: Each case keyword introduces a new pattern to match against the value.
- Wildcard _ Case: Acts as a default case, catching any values that don't match the specified patterns.
This structure ensures that only one case is executed, and there's no need for explicit break statements, making the code cleaner and less error-prone.