While loops & game loops
While a `for` loop repeats a specific number of times, a `while` loop continues running as long as a particular condition remains True. This makes while loops ideal for game engines and interactive bots.
- Understand the mechanics of while loop execution.
- Prevent accidental infinite loops using state updates.
- Construct a turn-based game loop with health counters.
while condition: loop execution, state updates, and guards.
Use while loops when you don't know the exact number of iterations beforehand (e.g. game loops, waiting for user input, search algorithms). Always ensure the condition will eventually become False.
Turn-based battle game loop
The loop continues while player and boss health are both greater than 0. Each turn applies damage until a victory condition is reached.
Memory Trace: While Loop Termination Condition
Follow how decrementing health triggers the loop exit condition.
| Variable | Value in Memory | Data Type |
|---|---|---|
| hp | 20 | int |
Initial health is 20.
hp = 20🔧 Infinite Loop Countdown Bug
A countdown loop forgot to decrement its counter variable, freezing the process.
Predict The Output (2 Questions)
Your lightbulb moment
The key takeaway
While loops repeat until their condition turns False. Every while loop must modify state toward termination to avoid infinite loops.
Make it yours
Try changing the damage to 15 to see how the boss is defeated in exactly 2 rounds.
Try editing the code in the playground above in Python, JavaScript, Java, or C++, and use the step-by-step Dry-Run Table to inspect how variables mutate in memory. If you get stuck, click the 🤖 AI Doubt Solver button on your screen for instant explanations!