Conditionals in Python: if / elif / else
Every frame of a game is a pile of decisions. if/elif/else is how you resolve them: hit an enemy? score. reached the bottom? lose a life. neither? carry on.
The big idea
if/elif/else picks exactly one block to run by testing conditions in order and stopping at the first one that is true.
See it in code
if/else picks one of two blocks to run. Python checks the condition, then takes whichever branch matches:
score = 100
if score > 0:
print("On the board!")
else:
print("No points yet.")On the board!
score > 0 was true, so the if branch ran and the else was ignored. Exactly one of the two always fires.
elif adds middle branches. Python tests each condition top to bottom and runs the first true one — the rest are skipped:
hit = True
at_bottom = False
if hit:
print("Direct hit! +100")
elif at_bottom:
print("Enemy got through")
else:
print("No collision this frame")Direct hit! +100
hit was true, so that branch fired and at_bottom was never even checked. elif and else only get a turn once every test above them fails.
Now wire that same ladder to real game objects. laser.hits(enemy) and enemy.at_bottom() each return True or False; with the laser sitting on the enemy, the collision test wins:
from game import Stage, Enemy, Laser, HUD
screen = Stage.create()
Stage.clear(screen)
hud = HUD()
enemy = Enemy(240, 300)
laser = Laser(240, 300)
if laser.hits(enemy):
hud.add_score(100)
print("Direct hit! +100")
elif enemy.at_bottom():
hud.lose_life()
print("Enemy got through")
else:
print("No collision this frame")
enemy.draw(screen)
hud.draw(screen)Direct hit! +100

Order matters: because the collision test was true, Python ran that branch and never even checked at_bottom(). elif and else only get a turn when every test above them came out false.
The same ladder drives decisions in every domain: classify a price move as up, down, or flat; route a web request by its path; bucket a DNA base into A, C, G, or T. Whenever exactly one of several outcomes should happen, if/elif/else is the shape.
Try it yourself
Move the laser to Laser(240, 100) so it misses, and set the enemy to Enemy(240, 570) so at_bottom() is true — now the elif fires and a life is lost. Then reorder the branches and watch the behavior change.
The common mistake
Using several separate ifs when you mean elif. Independent if statements are each checked, so two can fire in the same frame — scoring a hit and losing a life. elif guarantees only one branch runs.
What it unlocks
Conditions get sharper with comparison operators and boolean logic, and drive the collision detection at the heart of every game loop.