One-line choice and match
Pick a value with if and else on one line, or match one value against case lines.
- Write value-if-test-else-other
- Match one stored value against case lines
- Use case _ for every value you did not name
When each branch is just a value, you can choose it on one line:
label = "ship" if price >= 15 else "hold"
Read it as: ship when the test is true, otherwise hold. The whole line is a value, so you can print it or store it. It always needs both parts: a one-line choice without else is a syntax error.
Run each example to see what it prints. Running examples doesn't count toward progress.
price = 20 label = "ship" if price >= 15 else "hold" print(label)
match compares one value with several case lines. Python runs the first case that fits. case _ fits anything left over. _ is the wildcard: it matches any value and stores nothing. Use match when you are comparing one value against a list of known options; it reads more clearly than a long elif chain.
status = "delivered" match status: case "packing": print("Wait") case "delivered": print("Send") case _: print("Check")
- value if test else other chooses one of two values, and always needs the else.
- match runs the first case that fits. case _ fits every value you did not name.
- Store a value in each case, then use it once after the match. Next module: repeating with loops.