Loops and repetition

As programs grow, they often need to do the same thing more than once. This comes up quickly when generating pages, processing lists of data, or waiting for conditions to change. Python provides simple looping constructs that let us express repetition directly, instead of copying and pasting the same code.

Why programs need repetition

Repetition allows a program to scale beyond a single action. Instead of writing code once per planet or page, we can write code once and let Python repeat it as needed. This keeps programs shorter, clearer, and easier to change later.

Condition-controlled repetition with while

A while loop repeats as long as a condition remains true. Each repetition checks the condition again before continuing.

count = 0

while count < 3:
    print("Generating page")
    count = count + 1

This form is useful when we do not know in advance how many times the loop should run, only when it should stop.

Iterating over a sequence with for

A for loop is designed to step through a sequence of values, one at a time. The loop variable takes on each value in turn.

planets = ["Mercury", "Venus", "Earth"]

for planet in planets:
    print(planet)

This style fits naturally when processing collections of related items, such as a list of planets or filenames.

Controlling iteration with range

The range() function produces a sequence of numbers, which is commonly used with for loops to repeat a fixed number of times.

for i in range(3):
    print("Writing file", i)

This approach is useful when repetition is based on counts or positions rather than existing data.

Stopping repetition as conditions change

Loops often depend on values that change during execution. Updating those values allows repetition to stop naturally once the program’s goal is reached.

remaining = 5

while remaining > 0:
    print("Remaining:", remaining)
    remaining = remaining - 1

The loop ends as soon as the condition becomes false.

Conclusion

At this point, we are oriented to Python’s two main looping tools. We can repeat work based on conditions using while, or step through sequences using for. With these constructs, repetition becomes a clear part of program structure rather than something we work around.