Python Tutorials · Python Match

Python Match

Learn all about Python Match in this comprehensive tutorial.

5 min read beginner
  • The match statement is used to perform different actions based on different conditions.
  • Instead of writing **many** if.
  • Use the underscore character _ as the last case value if you want a code block to execute when there are not other matches:
  • Use the pipe character | as an or operator in the case evaluation to check for more than one value match in one case:
  • You can add if statements in the case evaluation as an extra condition-check:

Introduction

The match statement is used to perform different actions based on different conditions.

The Python Match Statement

Instead of writing many if..else statements, you can use the match statement.

The match statement selects one of many code blocks to be executed.

Syntax

python

This is how it works:

  • The match expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the associated block of code is executed.

The example below uses the weekday number to print the weekday name:

python

Default Value

Use the underscore character _ as the last case value if you want a code block to execute when there are not other matches:

python

The value _ will always match, so it is important to place it as the last case to make it behave as a default case.

Combine Values

Use the pipe character | as an or operator in the case evaluation to check for more than one value match in one case:

python

If Statements as Guards

You can add if statements in the case evaluation as an extra condition-check:

python

Module quiz

2 questions
1

Which of the following is true about Python Match?

2

What is the most common pitfall when working with Python Match?

Answer all questions to submit.