if, elif and else
Run code only when a condition is true. Python runs the first branch that matches.
Syntax
if condition:...elif other_condition:...else:...
- Each header line ends with a colon, and its block is indented.
Example
hp = 5
if hp > 10:
print("strong")
elif hp > 3:
print("hurt")
else:
print("critical")Output:
hurt
Common mistakes
- A missing colon after the condition is a SyntaxError.
- Order matters: put the most specific condition first.