Python Basics — Ternary Operator

2 minute read

Ternary Operator

Python’s ternary operator (also called a conditional expression) lets you write simple if-else logic in a single line.

Syntax

value_if_true if condition else value_if_false

It evaluates the condition, then returns one of two values.

Basic Examples

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

Output:

adult

Compare with the traditional approach:

# Traditional if-else — 4 lines
age = 20
if age >= 18:
    status = "adult"
else:
    status = "minor"

# Ternary — 1 line
status = "adult" if age >= 18 else "minor"

Both produce the same result. The ternary version is shorter and often clearer for simple cases.

Common Use Cases

Assigning Default Values

name = ""
display_name = name if name else "Anonymous"
print(display_name)  # Anonymous

Inline String Formatting

count = 1
print(f"You have {count} {'item' if count == 1 else 'items'}.")

Output:

You have 1 item.
count = 5
print(f"You have {count} {'item' if count == 1 else 'items'}.")

Output:

You have 5 items.

Function Arguments

def greet(name, formal=False):
    greeting = f"Dear {name}" if formal else f"Hey {name}"
    print(greeting)

greet("Alice", formal=True)   # Dear Alice
greet("Bob")                   # Hey Bob

Return Statements

def absolute_value(n):
    return n if n >= 0 else -n

print(absolute_value(-5))   # 5
print(absolute_value(3))    # 3

Nested Ternary (and Why to Avoid It)

You can chain ternary operators:

score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"
print(grade)  # B

Don’t do this. It’s hard to read and debug. Use regular if-elif-else instead:

score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

Ternary vs Traditional if-else

Aspect Ternary Traditional
Lines 1 4+
Readability Best for simple cases Best for complex logic
Nesting Avoid Use elif chains
Use in expressions Yes (inside f-strings, arguments) No
Debugging Harder Easier

When to Use Ternary

  • Simple true/false value assignment
  • Inline string formatting
  • Short function return values
  • Default value fallbacks

When NOT to Use Ternary

  • Complex conditions with multiple variables
  • When either branch has side effects
  • When nesting would be required
  • When the line becomes longer than ~80 characters

Summary

  • Syntax: value_if_true if condition else value_if_false
  • Great for simple, one-line conditional assignments
  • Works inside f-strings, function calls, and return statements
  • Never nest ternary operators — use regular if-elif-else instead
  • If the line gets hard to read, switch to traditional if-else

Next up: Match-Case →

Updated: