Bootcamp Curriculum • 5 Modules • 12 Chapters • Multi-Language Runner (Python, JS, Java, C++) • Interactive Memory Trace • AI Mentor
CHAPTER 08 · LOOPS5 min read

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.

By the end of this chapter, you can:
  • Understand the mechanics of while loop execution.
  • Prevent accidental infinite loops using state updates.
  • Construct a turn-based game loop with health counters.
Explanation DepthTailor the level of detail to your learning goal
💻 Standard College Notes

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.

💡break immediately terminates the loop; continue skips to the next condition check.

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.

example_1.py
Ctrl + ↵ to run
Terminal Output
Ready to execute
Click "▶ Run Code" or press Ctrl+Enter to compile & run this snippet.
✦ Interactive Dry-Run Visualizer

Memory Trace: While Loop Termination Condition

Follow how decrementing health triggers the loop exit condition.

STEP1 / 7
1hp = 20👉 Executing
2while hp > 0:
3 hp = hp - 10
4print('Done')
VariableValue in MemoryData Type
hp20int
Initialize hp counter

Initial health is 20.

Console Stream (stdout)
(No output generated yet)
Line 1: hp = 20

🔧 Infinite Loop Countdown Bug

A countdown loop forgot to decrement its counter variable, freezing the process.

⚡ +100 XP
fix_bug.pyPython 3.10
⚡ Quick Revision Quiz

Predict The Output (2 Questions)

Question 1 of 2:
How many times does this loop run? x = 5; while x > 0: x -= 2
Question 2 of 2:
What keyword immediately terminates a loop prematurely?

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!