if / elif / else + ternary
Conditional execution. Truthy values run the if branch; falsy values run else.
script.py
v3.1
Python output
click Run to execute
Click "Run" to execute the code on the left.
The output will appear here.
The output will appear here.
🧠 How it works
if condition: runs the block if condition is truthy. elif = 'else if'. else runs if nothing matched. Python has many falsy values: False, None, 0, 0.0, empty string '', empty list [], empty dict {}, empty set. Everything else is truthy — including non-empty containers, non-zero numbers, and any object. Ternary: value_if_true if condition else value_if_false — read it as 'X if condition else Y'. in checks membership: 'x' in [1, 2, 3], 'k' in dict, 'a' in 'apple'. Avoid '== True' — just use 'if x:' (Pythonic).
✏️ Try these changes
-
Change score = 78 to score = 95→ grade becomes A -
Change score = 78 to score = 50→ grade becomes F -
Add a value 0.0 to the values list→ 0.0 is falsy too -
Change the ternary to 'odd' if x % 2 else 'even'→ logic flips — both work