Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
Ternary (Conditional) Expressions
The ternary operator (conditional expression) lets you write simple if/else conditions in a single line. It's concise but should be used only for simple conditions.
Ternary Operator
# Syntax: value_if_true if condition else value_if_false
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # adult
# Examples
x = 10
result = "even" if x % 2 == 0 else "odd"
print(f"{x} is {result}")
# With functions
score = 85
print("Pass" if score >= 60 else "Fail")
# Nested ternary (avoid if complex!)
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"
print(f"Grade: {grade}")
# Better readability - use regular if/elif for complex casesTip
Tip
Use ternary for simple assignments: status = 'pass' if score >= 60 else 'fail'. Keep it to one line max.
Python checks each condition in order - the first True branch runs, then it exits
Common Mistake
Warning
Nesting ternary operators makes code unreadable. Use regular if/elif/else for anything beyond a simple condition.
Practice Task
Note
(1) Write an even/odd checker using ternary. (2) Create a greeting based on time of day. (3) Convert a nested ternary to regular if/elif.