Part 3: Python Programming

7. Loops

Loops

Computers excel at repetition. A loop runs a block of code many times without you writing it out again and again. Python has two loops: the for loop, which repeats once for each item in a sequence, and the while loop, which repeats as long as a condition stays true.

The for loop and range()

A for loop walks through the items of a sequence, giving you one item per pass. The range() function generates a sequence of numbers, which is the usual way to repeat a fixed number of times. range(5) produces 0, 1, 2, 3, 4 (it stops before 5):

PYTHON
for i in range(5):
    print(i)
▸ OUTPUT
0
1
2
3
4

range can take a start, stop, and step: range(2, 11, 2) gives 2, 4, 6, 8, 10.

Iterating over sequences

You can loop directly over the characters of a string or, as you will see later, the items of a list:

PYTHON
for letter in "cat":
    print(letter.upper())
▸ OUTPUT
C
A
T

The while loop

A while loop keeps going as long as its condition is true. You must make sure something inside the loop eventually makes the condition false, or the loop will run forever:

PYTHON
count = 3
while count > 0:
    print(count)
    count = count - 1
print("Lift off!")
▸ OUTPUT
3
2
1
Lift off!
start count = 3 count > 0 ? print, count = count - 1 Lift off! True False

break and continue

Two keywords give you finer control. break leaves the loop immediately. continue skips the rest of the current pass and jumps to the next one:

PYTHON
for n in range(1, 10):
    if n == 5:
        break
    if n % 2 == 0:
        continue
    print(n)
▸ OUTPUT
1
3

Odd numbers 1 and 3 print. Even numbers 2 and 4 are skipped by continue, and when n reaches 5 the break stops the loop entirely.

The loop else clause

Both loops may have an else block that runs only if the loop finished normally without hitting a break. It is handy for search loops:

PYTHON
for n in [4, 6, 8]:
    if n % 2 != 0:
        print("Found an odd number")
        break
else:
    print("All numbers were even")
▸ OUTPUT
All numbers were even

Choosing between for and while

Use a for loop when...Use a while loop when...
You know how many times to repeatYou repeat until a condition changes
You are walking through a sequenceThe number of repeats is unknown in advance
Example: process each studentExample: keep asking until input is valid

Loops turn a few lines of code into enormous amounts of work. Practice by printing a multiplication table for a number using a for loop and range.