Courses / Computer Science I
Programming I

Loops and Repeated Computation

Computer Science I 330 words Free to read

Doing It Again

A loop repeats a block of code. The two staple forms are the while loop and the for loop.

A while loop repeats as long as a condition stays true, checking the condition before each pass:

i = 0
while i < 5:
    print(i)
    i = i + 1

This prints 0 1 2 3 4. Three ingredients keep it correct: an initialization (i = 0), a condition (i < 5), and an update (i = i + 1) that moves toward making the condition false. Forget the update and the condition never becomes false — an infinite loop that runs forever.

A for loop is designed for a known number of repetitions or for stepping through a collection: for i in range(5) runs the body for i = 0, 1, 2, 3, 4. Note that range(5) gives five values starting at 0 and stopping before 5 — a convention that is the source of the classic off-by-one error, where a loop runs one time too many or too few because a boundary (< vs <=) is wrong.

Two control statements adjust a loop from inside: break exits the loop immediately, and continue skips to the next iteration. Loops can also nest, one inside another — a nested loop running mm times inside a loop running nn times executes its inner body n×mn \times m times, which matters for performance.

Common pitfall: the off-by-one error. A loop for i in range(5) runs for i = 0..4 (five times, stopping before 5), and while i <= 5 runs one more time than while i < 5. Always check whether the boundary should be included, and whether counting starts at 0 or 1.

A counter stepping along a number line from 0, ticking 0,1,2,3,4 under a "< 5" gate that turns the flow off exactly at 5 — the loop bound and the five iterations shown as discrete accent steps.

range(n):0,1,,n1\text{range}(n): 0, 1, \ldots, n-1

Loops and Repeated Computation

Practise this lesson

The explanation above is free to read. The graded practice for this lesson lives in the Tryals app.

11practice questions
2interactive scenes
Start Computer Science I free

Programming I