+160 XP
Next MissionLesson 6: While Loops and Game Loops
In games, you don't know in advance how long the player will stay alive. That is where While Loops shine! A while loop keeps running AS LONG AS a condition remains True.
Key Concepts to Remember:
- •The while Condition: Checks a condition: if True, runs code. Loops until the condition becomes False.
- •Counter Variable: Always update your counter variable inside the loop (like count = count + 1) so it doesn't run forever.
- •break Keyword: An emergency escape hatch that immediately stops and exits any loop.
- •Infinite Loop Caution: If a condition never turns False, the loop runs forever! Press Ctrl + C to freeze it.
💻Counting Down with While (IDE Syntax Colors)
energy = 3
while energy > 0:
print(f"Hero fighting! Energy: {energy}")
energy = energy - 1
print("Hero resting at camp!")
💡 The loop runs 3 times until energy reaches 0, then cleanly exits.
💡 Pro Tip: Make sure something inside the while loop changes the condition, otherwise it loops forever.