Loops

Lesson 5 of 20

Loops do the boring work — trace for and while as they count, accumulate and repeat without copy-paste.

The big picture

Repeat without repeating yourself

Loops let a few lines do the work of hundreds — for walks a sequence, while watches a condition.

for = Visitor

for i in range(3) hands i the values 0, 1 and 2 — one visit per value.

range = Number Factory

range(1, 4) yields 1, 2, 3 — it starts at the first number and stops before the second.

while = Watchman

Repeats the body as long as the condition stays True; it re-checks before every pass.

Update or Loop Forever

Inside a while, something must move the condition toward False — like count = count - 1.