Loading lessons...
Ternary Operator
Ternary Operator
The ternary operator packs an if/else into one line. It's also called a conditional expression.
The syntax
value = x if condition else y
If the condition is True, you get x; otherwise you get y.
Example
a = 330
b = 200
result = "a is bigger" if a > b else "b is bigger"
print(result) # a is bigger
Compare with a normal if
The same logic with a full if/else is longer:
if a > b:
result = "a is bigger"
else:
result = "b is bigger"
The ternary is the compact one-liner.
Multiple conditions
You can chain them, but keep it readable:
grade = "Pass" if score >= 60 else "Fail"
TL;DR
a if cond else bpicks one of two values.- It's the one-line replacement for a simple if/else.
- Use it for short choices; keep longer logic in full if/else.