runtime
20 / 250
lesson 20 Conditional Logic · beginner

One-line choice and match

Pick a value with if and else on one line, or match one value against case lines.

You'll be able to
  • Write value-if-test-else-other
  • Match one stored value against case lines
  • Use case _ for every value you did not name
The idea

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.

example-1.py · ship or hold
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.

example-2.py · Match a status
status = "delivered"
match status:
    case "packing":
        print("Wait")
    case "delivered":
        print("Send")
    case _:
        print("Check")
Review
  • 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.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

One-line choice and match — Conditional Logic · Runtime