Loops
How a computer does the same thing again, and again, and again.
Story — the courier on Main Street
Imagine a courier with a bag of letters and a row of five mailboxes, numbered 0 to 4. Their job is simple: walk to mailbox 0, drop off a letter, walk to mailbox 1, drop off a letter, and so on until every mailbox has been visited once.
That is what a loop is. The courier's position is the loop variable; the mailbox count is how many times the loop runs; the action of dropping a letter is the loop body.
Courier says
See it — drive the loop
Press Step to advance one tick, or Play to watch it run. Notice how i changes between iterations and how the mailboxes light up one at a time.
Text-only trace
- N = 5, i starts at 0, total starts at 0.
Try it — fix the order
The four lines below build a working loop, but they are out of order. Move them so the program is correct.
Drag the pieces — or tab to one and use the ↑/↓ buttons — to put the program in order.
total += itotal = 0for i in range(5):print(total)
Code it — five languages, one idea
The same loop in five popular languages. Notice what is the same (the three jobs: start, condition, step) and what is just punctuation.
total = 0
for i in range(5):
total += i
print(total) # 10Walk through it line by line
Each click of Next executes one line. Watch the variable panel on the right to see what the computer sees.
1total = 02for i in range(5):3total += i4print(total)
Quiz it — make it stick
No Dumb Questions
Real questions other learners asked on this page.
Why do programmers start counting at 0?
Habit, mostly — but a useful habit. When `i` is 0 you can use it as a direct offset into a list (the first item is at offset 0). Languages that start at 1 exist (Lua, MATLAB), and they trade arithmetic clarity for human intuition.What is the difference between a for loop and a while loop?
A for loop is a while loop in fancy clothes. Use a for loop when you know how many times you want to run something; use a while loop when you want to keep going until some condition flips.What happens if I never increment `i` inside a while loop?
The condition stays true forever and your program hangs. This is called an infinite loop. Most editors and runtimes will let you `Ctrl-C` your way out of one — but a deployed server will not.