
Code
Match and Case
When you compare one value against many options, a long
if/elif chain gets repetitive. Python 3.10+ has match:
def door(knock):
match knock:
case "one":
return "Who's there?"
case "two" | "three":
return "Coming!"
case _:
return "Go away!"
- Each
caseis checked in order; the first match wins. |means or:case "two" | "three":matches either.case _:is the catch-all. It matches anything else, likeelse.
Pip tip: Clean the input before matching, so
" North "and"NORTH"both work.
Assignment
Complete pip_command(command). The input is already cleaned
into word for you. Add cases so it returns:
| word | return |
|---|---|
"light" |
"The lantern glows." (done) |
"north" or "south" |
f"Pip sails {word}." |
"rest" or "sleep" |
"Pip curls up for a nap." |
| anything else | f"Pip doesn't know '{word}'." |
Complete pip_command(command). The input is already cleaned
into word for you. Add cases so it returns:
| word | return |
|---|---|
"light" |
"The lantern glows." (done) |
"north" or "south" |
f"Pip sails {word}." |
"rest" or "sleep" |
"Pip curls up for a nap." |
| anything else | f"Pip doesn't know '{word}'." |
main.py Python sleeping
Press Run to try your code, then Check to test it.