Conditional Expressions (Ternary)

Published by Brayan K

A conditional expression — Python's ternary — is the one-line form a if condition else b that evaluates to a when the condition is true and b otherwise.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Read the condition before choosing the value

The condition sits in the middle of a conditional expression, but Python tests it first. It then evaluates only one of the two result expressions. The value before if is chosen when the condition is truthy; the value after else is chosen otherwise. Assign the result when you want to use that choice later.

age = 16
ticket = "adult" if age >= 18 else "junior"
print(ticket)

age = 18
ticket = "adult" if age >= 18 else "junior"
print(ticket)

# ✅ Expected output:
# junior
# adult

The boundary belongs in the condition: an age equal to eighteen takes the adult branch because the comparison includes equality. Writing a shorter expression does not remove the need to test the boundary. Both possible results here are strings, so the code using ticket can treat it consistently.

A conditional expression chooses a value. Control Flow: Making Decisions in Python owns if/elif/else statement blocks, which can run several actions in a branch.

The unchosen branch does not run

You can safely leave an operation in one branch when the condition establishes that the operation is valid. A zero count makes an average unavailable; calculating the division before making the choice would still fail. Keep the potentially failing calculation inside the branch that needs it.

total = 12
count = 0
average = total / count if count > 0 else None
print(average)

count = 3
average = total / count if count > 0 else None
print(average)

# ✅ Expected output:
# None
# 4.0

The condition is part of the expression, not a promise to ignore errors that already happened. In the following program, computing candidate occurs before Python reaches the choice:

total = 12
count = 0
candidate = total / count
average = candidate if count > 0 else None
print(average)

# ✅ Expected error:
# ZeroDivisionError: division by zero

Move the division back into the true branch, as in the first program. When branch expressions call functions, the same rule applies: only the selected call runs. The small helper below records which call actually happened.

def choose(label):
    print("called:", label)
    return label

approved = False
result = choose("send") if approved else choose("hold")
print("result:", result)

# ✅ Expected output:
# called: hold
# result: hold

Returning a value from a function is explained in Functions in Python. The important observation here is that choosing the hold branch does not first call the send branch.

An expression must supply an else value

A statement can do nothing when a condition fails. An expression must still produce a value for the surrounding assignment or call, so its else part is required. Leaving it off is a syntax error, even if the condition happens to be true:

label = "ready" if True
print(label)

# ✅ Expected error:
# SyntaxError: expected 'else' after 'if' expression

Write the alternative explicitly. If the other case should perform no action at all, use a statement block instead of trying to make an incomplete expression.

ready = True
label = "ready" if ready else "waiting"
print(label)

# ✅ Expected output:
# ready

Do not replace the choice with and/or

A selected value may itself be falsy. A free delivery price is zero, and that is a real answer. Combining and and or can discard it and take a fallback you never intended:

member = True
print(0 if member else 3)
print(member and 0 or 3)

# ✅ Expected output:
# 0
# 3

The conditional expression selects a branch without testing its result again. Booleans & Truthiness explains why the and/or version treats zero as a reason to continue to the fallback.

Parentheses show how much of a larger expression is conditional

A conditional expression has lower precedence than addition. If you attach a greeting before the true branch without parentheses, the greeting belongs only to that branch. Put parentheses around the choice when both outcomes should be passed into the surrounding operation.

name = ""
print("Hello " + name if name else "Guest")
print("Hello " + (name if name else "Guest"))

# ✅ Expected output:
# Guest
# Hello Guest

The second line makes the intended grouping visible: select a name, then prepend the greeting. This is often clearer than relying on a reader to remember the precedence table. Parentheses can also let you split a long choice over several lines without changing its meaning.

A chain groups from the right, so the second choice below is the entire else branch of the first choice. Check the edges of each band. If there are several more bands, or each branch needs its own actions, an if/elif/else block will usually be easier to follow.

for score in [49, 50, 79, 80]:
    band = "high" if score >= 80 else ("middle" if score >= 50 else "low")
    print(score, band)

# ✅ Expected output:
# 49 low
# 50 middle
# 79 middle
# 80 high

In a comprehension, a conditional expression chooses the value for an item, while a trailing if filters items out. List, Dict & Set Comprehensions owns that distinction and its iteration syntax.

Fill in the delivery prices

Orders with a subtotal of at least twenty have free delivery. Other orders have a delivery price of three. Fill the two result values in the expression; leave the comparison in place. The examples test just below the boundary and exactly on it.

for subtotal in [19, 20]:
    delivery = ___ if subtotal >= 20 else ___
    print(subtotal, delivery, subtotal + delivery)

# 👉 replace ___ with 0
# 👉 replace ___ with 3

# ✅ Expected output:
# 19 3 22
# 20 0 20

Label readings without comparing a missing value

Build a report for the readings in the solution. An absent reading should have the label missing. A present reading at or below zero should have the label freezing; any higher reading should have the label above freezing. Use a statement to handle absence and a conditional expression to choose the two numeric labels. Print each reading with its label.

readings = [None, -2, 0, 7]
for reading in readings:
    if reading is None:
        label = "missing"
    else:
        label = "freezing" if reading <= 0 else "above freezing"
    print(reading, label)

# ✅ Expected output:
# None missing
# -2 freezing
# 0 freezing
# 7 above freezing

Practice quiz

What does this program print? age = 18 print("adult" if age >= 18 else "junior")

  • junior
  • adult
  • True
  • 18

Answer: adult. The boundary is included by >=.

What does this program print? print(1 / 0 if False else "safe")

  • A ZeroDivisionError
  • False
  • None
  • safe

Answer: safe. The division is inside the unchosen branch and is not evaluated.

What does this program print? print(0 if True else 3)

  • 0
  • 3
  • True
  • None

Answer: 0. The chosen result is retained even though zero is falsy.

What does this program print? name = "" print("Hello " + name if name else "Guest")

  • Hello Guest
  • Hello
  • Guest
  • An error

Answer: Guest. Addition belongs to the true branch here, so the false branch supplies Guest alone.

What does this program print? name = "" print("Hello " + (name if name else "Guest"))

  • Guest
  • Hello Guest
  • Hello
  • An error

Answer: Hello Guest. The parentheses make the choice an operand of the addition.

What does this program print? score = 50 print("high" if score >= 80 else ("middle" if score >= 50 else "low"))

  • high
  • low
  • True
  • middle

Answer: middle. The first condition fails; the else expression then chooses the middle band.

What does this program print? value = -2 print(value if value >= 0 else -value)

  • 2
  • -2
  • 0
  • False

Answer: 2. The false branch negates the negative number.

When is an if/else statement clearer than a conditional expression?

  • Whenever a condition compares numbers
  • Whenever the two values are strings
  • When each branch must perform several actions
  • Only when the condition is false

Answer: When each branch must perform several actions. A conditional expression chooses a value; a statement block can organise several actions.

Continue this course

Related lessons