Python Conditions · Lesson 31 of 149

Python Conditional Expressions

What you will learn

  • The conditional expression (also called the ternary operator)
  • How it differs from an if statement
  • Using it inside f-strings, comprehensions and function calls
  • That only one branch runs
  • Its difference from x or default, and when to avoid it

1. A choice that produces a value

An if statement chooses which code to run (lesson 5.2). Sometimes you only need to choose which value to use. A conditional expression does that in one line:

value_if_true if condition else value_if_false

age = 20
status = "adult" if age >= 18 else "minor"
print(status)
adult

Compare the long form:

if age >= 18:
    status = "adult"
else:
    status = "minor"

Both do exactly the same. The short form is an expression, so it can go anywhere a value can go. It has three parts, and the order is unusual: the condition is in the middle.

Part Role
"adult" the value if the condition is true
age >= 18 the condition
"minor" the value if it is false
Quick check: what does `"yes" if 0 else "no"` give?

"no". The number 0 counts as false, so the value after else is chosen.

2. Where it fits

Because it is an expression, you can use it in many places:

x = 7
print("even" if x % 2 == 0 else "odd")
print(f"{x} is {'even' if x % 2 == 0 else 'odd'}")
print([("big" if v > 10 else "small") for v in [5, 15]])
odd
7 is odd
['small', 'big']
  • directly as an argument to print or any function,
  • inside an f-string (use different quotes inside the braces, lesson 4.5),
  • inside a list comprehension (chapter 12), where it chooses the value to keep.

A popular use is plurals:

for count in (1, 3):
    print(f"{count} item{'s' if count != 1 else ''}")
1 item
3 items

3. Only one branch runs

Python works out only the branch it picks. The other one is never evaluated, so it cannot cause an error:

print(1 if True else 1 / 0)
1

The 1 / 0 would raise a ZeroDivisionError, but it is never reached. This makes the expression a safe guard:

lst = [1, 2]
first = lst[0] if lst else None
print(first)
print([][0] if [] else None)
1
None

For the empty list, [][0] would be an IndexError, but the condition is false, so it is skipped.

4. Chaining, and why to be careful

You can put one conditional expression inside another, and Python reads it from the left:

def sign(n):
    return "positive" if n > 0 else "negative" if n < 0 else "zero"

print([sign(v) for v in [5, -2, 0]])
['positive', 'negative', 'zero']

It works, but more than one level is hard to read. Use an if / elif / else instead (lesson 5.2) as soon as you need a second else.

5. Precedence: use brackets

The conditional expression has a very low priority, lower than or, + and the comparisons, so it takes in everything on its sides:

print(1 + 2 if True else 3 + 4)
print((1 + 2) if False else (3 + 4))
3
7

1 + 2 if True else 3 + 4 is (1 + 2) if True else (3 + 4). When the line is more complex, add brackets to show what you mean.

6. Compared with or

Lesson 5.3 showed value or default, which gives the default when value is false in any way:

name = ""
print(name or "Anonymous")
print(name if name else "Anonymous")
Anonymous
Anonymous

They agree here, but they are not the same when a valid value can be false, such as the number 0:

count = 0
print(count or 10)
print(count if count is not None else 10)
10
0

count or 10 replaced a perfectly good 0 by 10. When None is the only "missing" value, test it explicitly with is not None, using a conditional expression.

7. A trick to avoid: tuple indexing

You may see ("no", "yes")[condition]. A boolean works as 0 or 1, so it picks an item:

age = 20
print(("no", "yes")[age >= 18])
yes

It works, but both values are evaluated first, so it cannot guard against errors, and it is harder to read. Prefer the real conditional expression.

Worked example: a safe average

Make a function that gives the average of a list, or 0 if the list is empty (avoiding the division by zero).

def average(values):
    return sum(values) / len(values) if values else 0

print(average([70, 80, 90]))
print(average([]))
80.0
0
Step Reasoning
condition values is true when the list has items
if true sum(values) / len(values), the average
if false 0, and the division is never evaluated

The marks are made up for the example. (def and return come in chapter 11.)

Common mistakes

  • Forgetting the else part. The expression always needs it: "yes" if x is a syntax error.
  • Nesting several levels. Use if / elif / else instead.
  • Mixing up the order. The value comes first and the condition in the middle.
  • Using or for a default when 0 or "" is a valid value.
  • Expecting a tuple index to skip the other value. Both are evaluated.

Key takeaways

  • a if condition else b is an expression that gives a when the condition is true, otherwise b.
  • Only the chosen branch is evaluated, so it can guard against errors.
  • It fits inside f-strings, comprehensions and function arguments.
  • Keep it to one level; use an if statement for anything longer.
  • x or default also replaces 0 and ""; use x if x is not None else default when only None means "missing".

Practice

1. Write a one-line expression giving "pass" when marks >= 40, otherwise "fail".

Show answer

"pass" if marks >= 40 else "fail".

2. What does 10 if 5 > 7 else 20 give?

Show answer

20, because 5 > 7 is false.

3. Make "1 file" or "3 files" from a number n, using an f-string.

Show answer

f"{n} file{'s' if n != 1 else ''}".

4. Why is [] and 5 if False else 7 hard to trust, and how would you make it clear?

Show answer

It mixes and with a conditional expression, and the reader must remember the order of operations. Add brackets, such as ([] and 5) if False else 7, or split it into an if statement.

5. price might be 0 (a free item) or None (unknown). Write an expression that gives "unknown" only for None, and the price otherwise.

Show answer

"unknown" if price is None else price. Using price or "unknown" would wrongly turn 0 into "unknown".

6. Rewrite this as a one-line expression: if n % 2 == 0: then kind = "even", else: kind = "odd".

Show answer

kind = "even" if n % 2 == 0 else "odd".