Shorten your
if/else statements for compact, one-line value selection. It's also known as a conditional expression.#### π The Standard
if/else BlockThis is the classic, multi-line way to assign a value based on a condition.
# Check if a user is an adult
age = 20
status = ""
if age >= 18:
status = "Adult"
else:
status = "Minor"
print(status)
# Output: Adult
---
#### β The Ternary Operator (One-Line
if/else)The same logic can be written in a single, clean line.
Syntax:
value_if_true if condition else value_if_falseLet's rewrite the example above:
age = 20
# Assign 'Adult' if age >= 18, otherwise assign 'Minor'
status = "Adult" if age >= 18 else "Minor"
print(status)
# Output: Adult
---
π‘ More Examples
The ternary operator is an expression, meaning it returns a value and can be used almost anywhere.
1. Inside a Function
returndef get_fee(is_member):
# Return 5 if they are a member, otherwise 15
return 5.00 if is_member else 15.00
print(f"Your fee is: ${get_fee(True)}")
# Output: Your fee is: $5.0
print(f"Your fee is: ${get_fee(False)}")
# Output: Your fee is: $15.0
2. Inside an f-string or
print()is_logged_in = False
print(f"User status: {'Online' if is_logged_in else 'Offline'}")
# Output: User status: Offline
3. With List Comprehensions (Advanced)
This is where it becomes incredibly powerful for creating new lists.
numbers = [1, 10, 5, 22, 3, -4]
# Create a new list labeling each number as "even" or "odd"
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels)
# Output: ['odd', 'even', 'odd', 'even', 'odd', 'even']
# Create a new list of only positive numbers, or 0 for negatives
sanitized = [n if n > 0 else 0 for n in numbers]
print(sanitized)
# Output: [1, 10, 5, 22, 3, 0]
---
π§ When to Use It (and When Not To!)
β’ DO use it for simple, clear, and readable assignments. If it reads like a natural sentence, it's a good fit.
β’ DON'T use it for complex logic or nest them. It quickly becomes unreadable.
β BAD EXAMPLE (Avoid This!):
# This is very hard to read!
x = 10
message = "High" if x > 50 else ("Medium" if x > 5 else "Low")
β BETTER (Use a standard
if/elif/else for clarity):x = 10
if x > 50:
message = "High"
elif x > 5:
message = "Medium"
else:
message = "Low"
βββββββββββββββ
By: @DataScience4 β¨