Ternary Operator
The ternary operator (also called conditional expression) lets you write simple
if...else statements in a single line. It's perfect for assigning values based
on conditions - making your code more concise and Pythonic!
Basic Syntax
Python's ternary syntax is unique - it reads almost like English:
value_if_true if condition else value_if_false
Click Run to execute your code
condition ? value_if_true : value_if_false, Python uses explicit keywords:
value_if_true if condition else value_if_false. This makes it more readable!
Practical Uses
The ternary operator shines in specific scenarios like default values, formatting, and list comprehensions.
Click Run to execute your code
Nested Ternary (Use Sparingly!)
You can chain ternary operators for multiple conditions, but be careful - it can quickly become hard to read.
Click Run to execute your code
Ternary vs Traditional if-else
Knowing when to use each approach is key to writing clean, readable code.
Click Run to execute your code
Common Mistakes
1. Putting condition first (like other languages)
# Wrong - this is C/Java style!
# x > 0 ? "positive" : "negative" # SyntaxError!
# Correct - Python puts condition in the middle
result = "positive" if x > 0 else "negative"
2. Using ternary for side effects
# Wrong - confusing and bad practice
print("yes") if condition else print("no")
# Correct - use if-else for actions
if condition:
print("yes")
else:
print("no")
3. Over-nesting ternary operators
# Wrong - unreadable!
x = a if b else c if d else e if f else g
# Correct - use if-elif-else for multiple conditions
if b:
x = a
elif d:
x = c
elif f:
x = e
else:
x = g
4. Forgetting the else part
# Wrong - ternary requires both if and else!
x = "yes" if condition # SyntaxError!
# Correct
x = "yes" if condition else "no"
Exercise: Ticket Pricing
Task: Use ternary operators to determine prices and labels.
Requirements:
- If age is under 12, ticket price is $10; otherwise $20
- Determine if a number is "Even" or "Odd"
Click Run to execute your code
Show Solution
age = 10
# 1. Ticket Price (under 12: $10, else: $20)
price = 10 if age < 12 else 20
print(f"Age: {age}, Ticket Price: ${price}")
# 2. Even or Odd
number = 7
type = "Even" if number % 2 == 0 else "Odd"
print(f"Number: {number}, Type: {type}")
Summary
- Syntax:
value_if_true if condition else value_if_false - Use for: Simple value assignments, default values, inline formatting
- Avoid for: Multiple statements, complex logic, side effects
- Nesting: Possible but often hurts readability
- Always include: Both the if AND else parts (both are required)
What's Next?
Now that you can write concise conditionals, let's learn about for loops - the primary way to iterate over sequences and repeat actions in Python. This is where programming gets really powerful!
Enjoying these tutorials?