if / else — but faster, on one line
The problem...
You know how to write an if / else. It works. It's clear.
But sometimes four lines feel like a lot for a simple yes or no.
if score >= 60:
result = "Passed"
else:
result = "Failed"
Four lines. One decision. One variable. There's a shorter way.
The idea!
The ternary operator compresses a simple if / else into a single line.
result = "Passed" if score >= 60 else "Failed"
Same logic. Same outcome. One line.
The syntax
value = something if condition else something_else
Read it left to right: assign something — but only if condition is true — else assign something_else.
A few examples
age = 20
label = "Adult" if age >= 18 else "Minor"
print(label) # Adult
temperature = 15
feeling = "warm" if temperature > 20 else "cold"
print(feeling) # cold
is_logged_in = True
greeting = "Welcome back." if is_logged_in else "Please log in."
print(greeting) # Welcome back.
Use it — but don't abuse it
Ternary is clean when the condition is simple. It becomes a problem when you try to do too much.
# Fine — simple and readable
status = "on" if is_active else "off"
# Avoid — too much on one line, hard to read
result = "A" if score >= 90 else "B" if score >= 70 else "C"
The moment it gets hard to read — switch back to if / elif / else. Ternary is a tool, not a rule.
Common mistakes
# Wrong — condition at the wrong place
result = if score >= 60 "Passed" else "Failed" # SyntaxError
# Wrong — trying to run code, not assign a value
if score >= 60 else print("Failed") # SyntaxError
# Wrong — nesting ternaries
result = "A" if score >= 90 else "B" if score >= 70 else "C"
# works, but nobody wants to read this
Ternary assigns a value — it doesn't run blocks of code. And it doesn't replace elif.
Heads up!
- Ternary only works for simple
if / else— noelif - The condition goes in the middle —
value if condition else other - If it's hard to read on one line — use the full
if / elseinstead - Never nest ternaries — it's not clever, it's unreadable
The mindset shift
Stop thinking: "I need four lines for every decision."
Start thinking: "If it's simple enough to say in one sentence — write it in one line."
What you should understand now
- Ternary is a compressed
if / elseon a single line - Syntax:
value if condition else other_value - Use it for simple binary decisions — not for complex logic
- Readability always wins — if it's unclear, use the full form