We can't find the internet
Attempting to reconnect
Something went wrong!
Attempting to reconnect
← Pattern Matching, f-Strings and Newer Syntax step 8 of 23
Answer Chat Commands with match and case
You are writing a help-desk chat bot. A message is either text the user typed or a number they picked from a menu. The bot answers each one:
reply("hello") # 'Hello!'
reply(3) # 'You picked option 3.'
reply("help") # 'Unknown command: help'
Write reply with one match statement. The previous article,
"Branch on a Value with match and case", shows every pattern you need.
What to write
Fill in reply(message). Check the rows in this order and return the
answer for the first one that fits:
| Message | Answer |
|---|---|
"hi" or "hello" |
"Hello!" |
"bye" |
"Goodbye!" |
"" |
"Say something." |
any int n |
f"You picked option {n}." |
any other text t |
f"Unknown command: {t}" |
Each row is one case:
- Use
|to put"hi"and"hello"in one case. - Use
int() as nto match any integer and give it a name. - End with a capture pattern, a bare name such as
case other:, which matches whatever is left. It has to be the last case, or Python refuses to run the file.
Edge cases
- Text must match exactly.
"Hi"and"bye "are unknown commands. 0and negative numbers are still menu numbers.
What the driver checks
Keep solve as it is. It calls reply on each message and returns the
answers in order. No messages gives an empty list.
Your code, saved here
Sign in to access your accepted solutions and saved draft history. You can keep reading the lesson without an account.
Sign in to your accountStuck?
Python reference solution
Sign in to track your attempts toward unlocking the reference solution.