if — Intermediate Playground
Starts a conditional statement; executes block only if condition is true
Python Playground
# Ternary expression
x = 42
label = "even" if x % 2 == 0 else "odd"
print(f"{x} is {label}")
# Nested ternary (use sparingly)
score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"
print(f"Score {score}: Grade {grade}")
# In list comprehensions
nums = range(1, 11)
labels = [f"{n}: {'even' if n % 2 == 0 else 'odd'}" for n in nums]
print(labels[:4])
Output
Click "Run" to execute your code
The ternary expression 'x if condition else y' is useful in assignments and comprehensions. Avoid nesting more than one level.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?