match and case Basics
Branch on value patterns.
Structural Pattern Matching
Python 3.10 introduced structural pattern matching with the match statement. It compares a value against a series of patterns and runs the first one that matches, far more powerful than chained if/elif.
Basic Syntax
Write match followed by the subject, then one or more case blocks. The first matching case runs.
command = 'start'
match command:
case 'start':
print('Starting up')
case 'stop':
print('Shutting down')
# prints: Starting upAll lessons in this course
- match and case Basics
- Matching Sequences and Mappings
- Class Patterns
- Guards and Wildcards