An if/else that fits inside one expression: pick one of two values.
# value_if_true if condition else value_if_false
age = 20
status = "Adult" if age >= 18 else "Minor"
# ans: status is "Adult"
# ternary with numeric values
x = 10
result = "Big" if x > 5 else "Small"
# ans: result is "Big"
# ternary inside ternary
score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C"
# ans: grade is "B"
Read it left to right: the first True condition picks the value just before it.
# use in variable assignment
x = 5
y = x * 2 if x > 3 else x + 2
# ans: y is 10 (the condition is True)
# use directly in print
x = 10
print("Even" if x % 2 == 0 else "Odd")
# ans: Even
Predict the value, then press → to see which side is picked.
# what is result?
x = 10
result = "Big" if x > 5 else "Small"
# ans: "Big"
# what about this?
x = 0
y = x if x else 10
# ans: 10 (x is falsy)
# nested ternary?
score = 75
grade = "A" if score >= 90 else "B" if score >= 80 else "F"
# ans: "F" (it fails both conditions)
# ternary with a calculation?
x = 5
y = x * 2 if x > 3 else x + 2
# ans: 10 (the condition is True)
# what is message?
is_valid = True
message = "Valid" if is_valid else "Invalid"
# ans: "Valid"
# tricky: what happens?
x = 5
y = 10 if x > 3 else 20 if x > 1 else 30
# ans: 10 (the first condition is True)
# what is assigned?
x = None
y = x if x is not None else "default"
# ans: "default"
# boolean ternary?
x = True
result = 1 if x else 0
# ans: 1
# what is the value?
x = -5
abs_x = x if x >= 0 else -x
# ans: 5
# what happens?
x = []
result = "Full" if x else "Empty"
# ans: "Empty"
# complex condition?
x, y = 5, 10
result = "Yes" if x > 0 and y > 0 else "No"
# ans: "Yes"
a if cond else b: the condition is evaluated first.
The else is required: the expression must produce a value either way.
The first True condition wins. Keep nesting shallow so it stays readable.