Often you want to pick one of two values based on a condition. The long way is an if/else statement:
age: int = 20
if age >= 18:
status: str = "adult"
else:
status = "minor"
That’s five lines for a simple choice. Python offers a one-line shortcut called the ternary operator (also called a conditional expression):
age: int = 20
status: str = "adult" if age >= 18 else "minor"
That’s the whole pattern:
<value-if-true> if <condition> else <value-if-false>
Read it left to right: “give me 'adult' if age >= 18, otherwise 'minor'”.
When to use it
The ternary shines when you’re assigning or passing a value:
# pick a discount based on membership
member: bool = True
discount: float = 0.20 if member else 0.05
# print one of two messages
print("Pass" if score >= 50 else "Fail")
# in an f-string
print(f"You have {n} item{'s' if n != 1 else ''}")
When NOT to use it
Skip the ternary when:
- The branches do something (calling functions, printing) rather than just produce a value
- The condition is long or complex
- Nesting starts to creep in
Nested ternaries quickly become unreadable:
# painful
grade: str = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"
# better
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
A good rule: if you can’t read the ternary at a glance, use if/else.
A note on and/or tricks
You may see code like this in older Python:
status = age >= 18 and "adult" or "minor"
It works most of the time — but breaks subtly when the “true” value is falsy (0, "", []). The ternary doesn’t have this trap. Always prefer the ternary.
Summary of Section 3
You now know every operator Python has:
- Arithmetic —
+ - * / // % ** - Comparison —
== != < > <= >= - Logical —
and or not - Assignment —
= += -= *= /= //= %= **= - Membership —
in not in - Identity —
is is not - Ternary —
x if cond else y
These plus variables and types are enough to write small programs. From here we’ll start putting them together — first with control flow (decisions and loops), then with functions.
What’s next
Section 4: Control Flow — making your program take different paths and repeat actions.