Iterative Statements: for, while, break and continue

50 min read Flow of Control

This is a free course. Log in to run the code exercises and track your progress.

Iterative Statements: for, while, break and continue

for iterates over a sequence, often range(start, stop, step); while repeats as long as a condition is True. break leaves the loop, continue jumps to its next pass.

n = 5
fact = 1
for i in range(1, n + 1):
    fact *= i
print(fact)       # 120

Loops also compute the sum of a series. For 1 + x + x² + ... + xⁿ, add x ** i for i from 0 to n:

x, n = 2, 4
s = 0
for i in range(n + 1):
    s += x ** i
print(s)          # 1 + 2 + 4 + 8 + 16 = 31

A loop can have an else part. It runs when the loop ends normally, but not after a break. That is handy in a prime test: the else runs only if no divisor was found.

n = 29
for d in range(2, int(n ** 0.5) + 1):
    if n % d == 0:
        print("Composite")
        break
else:
    print("Prime")
Python exercise

Read x and n from one line and print the sum of the series 1 + x + x^2 + ... + x^n.

x, n = map(int, input().split())
s = 0
for i in range(n):  # check the range: x**n must be included
    s += x * i
print(s)

Log in to edit and run this code.