044. Ternary Operator
Inline conditional expressions for simple choices
044. Ternary Operator
RAM Manager: Status Labels
Aryan’s RAM manager needs one-liner utility functions — things that C developers write as cond ? a : b but Python writes differently:
# C: n >= 0 ? n : -n
# Python: n if n >= 0 else -nNotice Python puts the true value first, then the condition, then the false value. This trips up everyone coming from C, Java, or JavaScript.
His broken code uses full if/else blocks where ternary expressions would be cleaner. The tests verify behavior — the bug is in how plural works: the broken version produces “3 items” correctly but fails on plural(0, "item") because count != 1 is True for 0, so it returns “0 items” — which is actually correct. The real bug is that absolute uses > instead of >= so absolute(0) returns 0 correctly but absolute(-0.0) would return the wrong sign. Use the ternary.
💡 Fun fact: Python’s ternary syntax value_if_true if condition else value_if_false reads like natural English, which was intentional. In contrast, C’s condition ? true : false puts the condition first — a historical accident from when Dennis Ritchie designed C in 1972. Python’s creator Guido van Rossum actually disliked the idea of a ternary operator for years before accepting the English-word version in Python 2.5 (2006).
⚠️ Watch out: Never nest ternary operators — a if c1 else b if c2 else d is technically valid Python but nearly impossible to read. The Python style guide (PEP 8) strongly discourages nested ternaries. If you find yourself nesting them, write a proper if/elif/else block instead.
🤔 Think about it: n if n >= 0 else -n computes absolute value. Python also has a built-in abs(n). What does the existence of abs() tell you about when to write a ternary vs. when to look for a built-in — and can you think of three other common one-liner patterns that Python has already turned into named functions?
Learning objectives
- Write ternary expressions with “value_if_true if condition else value_if_false”
- Use ternary for simple inline value selection
- Know when to use ternary vs full if/else
Key concepts
- ternary operator
- conditional expression
- inline if
Try it
Concept detail
Python’s conditional expression (ternary): value_if_true if condition else value_if_false
Unlike C’s ternary (condition ? a : b), Python puts the TRUE value first. This reads like English: “give me x if the condition holds, otherwise y”
x = n if n >= 0 else -n # absolute value label = “odd” if n % 2 else “even” # odd/even label default = value if value else “N/A” # provide default for falsy values
It’s an expression (returns a value), not a statement. You can use it anywhere an expression is allowed: in assignments, return statements, function calls, lists.
results = [x if x > 0 else 0 for x in numbers] # in list comprehension print(“yes” if ok else “no”) # in function call
When NOT to use ternary:
- Complex conditions: use if/else for readability
- Multiple choices: use if/elif/else
- Side effects: avoid side-effecting expressions in ternary
- Never nest ternaries: a if cond1 else b if cond2 else c (unreadable)
Solution
def absolute(n):
return n if n >= 0 else -n
def clamp(value, min_val, max_val):
if value < min_val:
return min_val
elif value > max_val:
return max_val
else:
return value
def plural(count, word):
suffix = "" if count == 1 else "s"
return f"{count} {word}{suffix}"Tests
def test_absolute_positive():
assert absolute(5) == 5
def test_absolute_negative():
assert absolute(-7) == 7
def test_absolute_zero():
assert absolute(0) == 0, "absolute(0) should be 0, not -0. Bug: n > 0 is False for 0, so it returns -0"
def test_clamp_in_range():
assert clamp(5, 1, 10) == 5
def test_clamp_below():
assert clamp(-5, 1, 10) == 1
def test_clamp_above():
assert clamp(15, 1, 10) == 10
def test_plural_one():
assert plural(1, "item") == "1 item"
def test_plural_many():
assert plural(3, "item") == "3 items"
def test_plural_zero():
assert plural(0, "item") == "0 items"