+91 81900 98289

Python Match

This Python Match lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

match compares one value against patterns. It needs Python 3.10 or newer. case _ is the fallback.

Use it when one command name chooses among several actions. An if chain is still fine for simple ranges.

Example 1: Start here

The try-it runner on this page supports match.

command = "start" # text match command: # compare this value with each case case "start": # runs when the value matches this pattern print("Batch opened") case "stop": # runs when the value matches this pattern print("Batch closed") case _: # the fallback when nothing above matched print("Unknown command")

Example 2: Match a word

match compares one value with each case. The underscore is the fallback.

day = "Mon" # text match day: # compare this value with each case case "Mon": # runs when the value matches this pattern print("Start") case "Fri": # runs when the value matches this pattern print("Review") case _: # the fallback when nothing above matched print("Class")

Example 3: Match a number

The case value is compared with seats.

seats = 0 # a whole number match seats: # compare this value with each case case 0: # runs when the value matches this pattern print("Empty") case _: # the fallback when nothing above matched print("Open")

Example 4: Capture the rest

A bare name in a case stores the value so you can print it.

command = "help" # text match command: # compare this value with each case case "run": # runs when the value matches this pattern print("Running") case other: # runs when the value matches this pattern print("Unknown", other) # a comma prints each value, with a space between
The try-it runner on this page supports match.
Call Now 81900 98289