Skip to content
Programming Foundations with Python
Path outline

Lesson

Loops

Repeat work and maintain a running result.

Repeating an instruction

A loop performs the same kind of work for several values. Python's for loop visits the items in a sequence. range(start, stop) generates integers beginning at start and ending just before stop. The excluded endpoint is important: range(1, 5) visits 1, 2, 3, and 4.

A while loop repeats while its condition is true. Its body must eventually change something that makes the condition false. Otherwise the program does not finish and the judge can stop it for exceeding the time limit.

A complete example

This program adds the squares of the integers from 1 through n.

Python 3
def square_sum(n):
    total = 0
    for value in range(1, n + 1):
        total += value * value
    return total

n = int(input())
print(square_sum(n))

For input 3, the output is 14 because 1 + 4 + 9 = 14. Before the loop, total is zero. After visiting value k, total contains the sum of the first k squares. That sentence is an invariant: it explains what remains true as the loop advances.

A sum starts at zero. A product usually starts at one. Starting a product at zero makes every later multiplication zero, which is a common factorial mistake.

Direction and nesting

range(n, 0, -1) counts downward from n to 1. The third argument is the step. A negative step is necessary when the sequence descends.

A nested loop runs one loop inside another. To print a triangle, the outer loop chooses a row and the inner loop chooses values in that row. A loop running n times inside another n-step loop can perform about n squared iterations. Read the constraints before using nested loops.

Printing several values

print(value) creates a new line. print(value, end=" ") prints a space after the value instead. Finish the row with print() when it is complete. Match the exact requested shape and avoid adding labels or debugging output.

Practice and check

Trace the example for n = 1 and n = 3. Write down total after each iteration, then compare your trace with the program.

The required exercises practice countdown, factorial, even-number sums, and nested loops. Their statements ask for functions, so retain the definition and call around your loops. The optional global-variable exercise demonstrates shared state. Prefer a returned value in ordinary solutions because the caller can see where the result comes from.

If a loop runs too many or too few times, inspect its endpoint first. If the answer always resets, make sure the accumulator is initialized before the loop, not inside it.

Sign in to save your progress.

Sign in

Practice