match and case: choose by value

Making Decisions, lesson 6 of 6

🔀 Making Decisions, lesson 6 of 6

match and case: choose by value

Pick a branch by matching one value against several cases, with | for alternatives and _ as the default.

10 min

1 exercise

1 quiz

0/2 solved

Getting Python ready… examples can run in a moment.

Use a match statement when one value is compared with several fixed options. Each case names a value, and Python runs the first case that matches. It works like an if / elif chain where each line checks ==, and case _: plays the role of else.

Example

Matching values

Change day to 3, then to 6. The _ is a wildcard: it matches anything, so it works as the default, like else.

Example

Alternatives with |

| reads as "or": the block runs if the value is any of the listed options. Try "Friday" and "Monday".

Quiz

What does this print?

Exercise

Traffic light

The program reads a traffic light colour with input(). Use match light: to set message:

  • "red" → Stop
  • "yellow" → Slow down
  • "green" → Go
  • anything else → Unknown light

The checker runs your code with several different colours, so the message has to depend on what is typed.

Your program receives this input: red