Python Ternary Operator: x if condition else y
A conditional expression picks one of two values in a single line: x if condition else y. It is also called the ternary operator.
Read if, elif, else first.
Choose a value in one line
These two programs do the same thing.
battery = 15
if battery <= 20:
status = "low"
else:
status = "ok"
print(status)
status = "low" if battery <= 20 else "ok"
print(status)
Both print low. Python works out the condition in the middle first. When it
is True the result is the value on the left; when it is False, the value on
the right. Only the chosen side is evaluated.
Use it inside other code
A conditional expression is a value, so it can go anywhere a value can: an argument, a return value, or an f-string.
def plural(count):
return "item" if count == 1 else "items"
for count in [1, 3]:
print(count, plural(count))
battery = 15
print(f"Battery is {'low' if battery <= 20 else 'ok'}")
This prints 1 item, 3 items, then Battery is low.
When not to use it
The key difference: an if statement runs blocks of code, while a conditional
expression produces one value. Use the expression when you are choosing a value
to store, return or print. Use an if statement when each branch does work.
The expression must always have an else:
status = "low" if battery <= 20 # SyntaxError: expected 'else'
Chaining them works, but quickly gets hard to read:
battery = 35
status = "low" if battery <= 20 else "medium" if battery <= 50 else "high"
print(status)
This prints medium. With three or more choices, an if/elif/else
statement is usually clearer.
Note: Keep both values the same kind (both strings, both numbers). Mixing them makes the code that uses the result harder to get right.
See also: Defining Functions, String Formatting.
Your turn
Write a function grade(score) that returns "pass" when score is 50 or
more and "fail" otherwise, using one conditional expression. Then print the
result for each score.
scores = [72, 49, 50]
# define grade(score) with one conditional expression, then loop over scores and print grade(score)
Expected output
pass
fail
pass