Conditional Expressions (Ternary)

Reviewed & 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.

It's perfect for choosing between two values inline: setting a default, labeling a number, or transforming items inside a comprehension — all without a multi-line if/else block.

What You'll Learn in This Lesson

1 a if condition else b

The value you usually want comes first, then the condition, then the fallback. It reads almost like a sentence:

age = 20

# The four-line if/else...
if age >= 18:
    status = "adult"
else:
    status = "minor"

# ...collapses to one expressive line
status = "adult" if age >= 18 else "minor"
print(status)            # adult

# Common: pick the larger of two numbers
a, b = 7, 12
bigger = a if a > b else b
print(bigger)            # 12

📐 The anatomy of a ternary:

  "adult"   if   age >= 18   else   "minor"
  ^^^^^^^         ^^^^^^^^^^^         ^^^^^^^
  if true        condition          if false

Read it as: "Give me adult, if age is 18 or more, otherwise minor."

# Pick between two values inline
temp = 28
label = "hot" if temp >= 25 else "mild"
print(label)             # hot

# A safe-division default
def divide(a, b):
    return a / b if b != 0 else 0

print(divide(10, 2))     # 5.0
print(divide(10, 0))     # 0

# Drop it straight into an f-string
count = 1
print(f"You have {count} item{'s' if count != 1 else ''}")
# You have 1 item

# ✅ Expected output:
# hot
# 5.0
# 0
# You have 1 item

🔁 Ternaries Inside Comprehensions

A ternary lets you transform every item in a comprehension based on a condition. Here the if/else goes at the front (transform), not the trailing filter position:

scores = [55, 80, 42, 91, 67]

# Label each score (keeps ALL items)
labels = ["pass" if s >= 60 else "fail" for s in scores]
print(labels)            # ['fail', 'pass', 'fail', 'pass', 'pass']

# Cap every value at 100
raw = [88, 105, 99, 130]
capped = [v if v <= 100 else 100 for v in raw]
print(capped)            # [88, 100, 99, 100]

2 Nesting & When NOT to Use a Ternary

You can chain ternaries to mimic if/elif/else, but readability drops quickly. Compare these grade examples:

score = 75

# A nested ternary (chains right to left)
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"
print(grade)             # C

# The same logic as a clearer if/elif/else
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
print(grade)             # C

🎯 Your Turn: Fill in the Blanks

Replace each ___ to complete the ternary expressions so the output matches.

# 🎯 YOUR TURN: replace each ___ to match the expected output
n = 7

# 1. 'even' or 'odd' -> 'odd'
parity = "even" if n % 2 == 0 ___ "odd"
print(parity)

# 2. Absolute value with a ternary -> 5
x = -5
abs_x = x if x >= 0 ___ -x
print(abs_x)

# 3. In a comprehension: label each as 'big'/'small' (cutoff 10)
vals = [4, 15, 9, 22]
tags = [___ for v in vals]
print(tags)   # ['small', 'big', 'small', 'big']

# Expected output:
# odd
# 5
# ['small', 'big', 'small', 'big']
parity = "even" if n % 2 == 0 else "odd"
abs_x = x if x >= 0 else -x
tags = ["big" if v >= 10 else "small" for v in vals]

Common Errors & How to Fix Them

status = age >= 18 ? "adult" : "minor"   # SyntaxError!

✅ Python has no ?:. Write status = "adult" if age >= 18 else "minor".

❌ Forgetting the else branch

label = "ok" if score >= 60   # SyntaxError - else is required

✅ A conditional expression must have an else. (A trailing if with no else is only for filtering inside comprehensions.)

❌ Putting statements in a branch

x = (print("hi") if flag else log())   # works but it's a misuse

✅ Ternaries are for choosing a value, not running statements. If each branch does work, use a real if/else block.

🎯 Mini Challenge: Pluralizer

Use ternaries to format counts with correct grammar and a friendly default.

# Mini Challenge: grammatical counts with ternaries
def describe(count, noun):
    word = noun if count == 1 else noun + "s"
    amount = count if count > 0 else "no"
    return f"{amount} {word}"

print(describe(1, "apple"))    # 1 apple
print(describe(3, "apple"))    # 3 apples
print(describe(0, "apple"))    # no apples

# Bonus: label a temperature with a chained ternary
def feel(t):
    return "hot" if t >= 30 else "warm" if t >= 20 else "cool"

print(feel(35))   # hot
print(feel(22))   # warm
print(feel(10))   # cool

# Expected output:
# 1 apple
# 3 apples
# no apples
# hot
# warm
# cool

📚 Keep Learning

Go deeper with the official Python documentation:

Frequently Asked Questions

Lesson complete — one-liners with confidence!

You can choose between two values with a if cond else b, drop it into f-strings and comprehensions, and you know when to stop nesting and switch to a full if/elif/else.

Practice quiz

What is the correct syntax for a Python conditional expression?

  • condition ? a : b
  • if condition then a else b
  • a if condition else b
  • a unless b if condition

Answer: a if condition else b. Python's ternary is 'a if condition else b' — the value comes first, then the condition, then the fallback.

What does "adult" if age >= 18 else "minor" evaluate to when age is 20?

  • "adult"
  • "minor"
  • True
  • 20

Answer: "adult". Since 20 >= 18 is true, the expression evaluates to the first value, "adult".

Why is a ternary called an expression rather than a statement?

  • Because it must be on one line
  • Because it cannot contain conditions
  • Because it always returns None
  • Because it produces a value you can assign, return, or pass

Answer: Because it produces a value you can assign, return, or pass. A conditional expression evaluates to a value, so you can assign it, return it, or drop it into a call or comprehension.

What does [x if x % 2 == 0 else 0 for x in [1,2,3,4]] produce?

  • [2, 4]
  • [0, 2, 0, 4]
  • [1, 0, 3, 0]
  • [0, 0]

Answer: [0, 2, 0, 4]. A leading ternary transforms every item, replacing odd numbers with 0: [0, 2, 0, 4].

What is the difference between a leading and a trailing if in a comprehension?

  • A leading if/else transforms every item; a trailing if filters items
  • They are the same
  • A leading if filters; a trailing if/else transforms
  • Only trailing ifs are valid

Answer: A leading if/else transforms every item; a trailing if filters items. [x if c else y for x in xs] transforms each item; [x for x in xs if c] filters items out.

How does the chained ternary "A" if s>=90 else "B" if s>=80 else "C" group?

  • Left to right
  • It is a syntax error
  • Right to left, like if/elif/else
  • It evaluates all branches first

Answer: Right to left, like if/elif/else. Nested ternaries chain right-to-left, mimicking if/elif/else — but readability drops fast beyond one level.

Is the else branch required in a conditional expression?

  • No, it is optional
  • Yes, a conditional expression must have an else
  • Only inside comprehensions
  • Only when assigning to a variable

Answer: Yes, a conditional expression must have an else. A ternary always needs an else. A trailing if with no else is only valid as a comprehension filter.

What does the C-style status = age >= 18 ? "adult" : "minor" cause in Python?

  • It works the same as the ternary
  • A TypeError
  • It returns a boolean
  • A SyntaxError — Python has no ?: operator

Answer: A SyntaxError — Python has no ?: operator. Python has no ?: operator; that C-style syntax is a SyntaxError. Use 'a if cond else b' instead.

When should you choose a full if/elif/else over a ternary?

  • When choosing between two simple values
  • When each branch needs multiple statements or its own logic
  • Never — ternaries are always better
  • Only inside functions

Answer: When each branch needs multiple statements or its own logic. A ternary holds one expression per branch; use a full block when branches need multiple statements or side effects.

What does abs_x = x if x >= 0 else -x compute when x is -5?

  • -5
  • 0
  • 5
  • None

Answer: 5. Since -5 >= 0 is false, the expression takes -x, which is -(-5) = 5 — an inline absolute value.

Continue this course

Frequently asked questions

What is a conditional expression (ternary) in Python?

It's a one-line way to choose between two values based on a condition, written 'value_if_true if condition else value_if_false'. Unlike a full if/else statement, it's an expression — it produces a value — so you can assign it, return it, or drop it inside a function call or a comprehension.

Why is Python's ternary order so unusual?

Most languages write condition first (cond ? a : b), but Python puts the result first: 'a if cond else b'. It reads almost like English — 'use a, if the condition holds, otherwise b'. The value you most often want is up front, and the fallback is at the end after else.

Can I nest ternary expressions?

You can — 'a if c1 else b if c2 else c' is valid and chains right-to-left like an if/elif/else. But it gets hard to read fast. One level is fine; two or more is usually a sign you should switch to a normal if/elif/else block or a lookup dictionary for clarity.

When should I use a full if/else instead?

Use the ternary when you're choosing between two simple values for one variable or expression. Switch to a full if/else statement when each branch needs multiple statements, side effects, or its own logic — the ternary can only hold a single expression per branch, so cramming more in hurts readability.