The Infinite Loop, and How to Avoid It

Every while loop needs three things. Miss any one and it runs forever:

1. A variable initialized before the loop

2. A condition that can eventually become false

3. Something inside the loop that moves toward that false

Forget step 3 and the condition never changes. The program hangs.

✦ You are protected here

The Sankofa sandbox stops runaway JavaScript after four seconds and tells you what happened, so you can experiment without fear. On your own machine there's no such net, Ctrl+C is how you stop it. Learning to spot the missing update is the real skill.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Fix the JavaScript version: add the line that makes count go up inside the loop, then run it.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Choosing While or For →
← Back