Loops

Level 3 of Python School: 3 lessons, explained from scratch, with examples.

Lesson 1

for loops and range()

Repeat code a set number of times.

Repeat with for

for i in range(3): runs the indented lines under it 3 times.

Like if, the line ends with a colon and the lines inside are indented.

Python
for i in range(3):
    print("Hip hip hooray!")

Counting with range()

Each time round the loop, the variable (here n) holds the next number from the range:

  • range(5) gives 0, 1, 2, 3, 4: five numbers, starting at 0
  • range(1, 6) gives 1, 2, 3, 4, 5: it stops before the second number
  • range(0, 10, 2) counts in steps of 2: 0, 2, 4, 6, 8
Python
for n in range(1, 6):
    print(n)

Practise “for loops and range()” in the game

Lesson 2

while loops

Keep going while something is true, and stop with break.

Repeat while it’s true

while condition: checks the condition, runs the lines inside if it’s true, and then checks again, over and over.

Something inside has to change, so the condition becomes false one day. If not, the loop goes on forever. (Here, the game stops it after a few seconds.)

Python
count = 3
while count > 0:
    print(count)
    count -= 1
print("Lift off!")

break and continue

  • break leaves the loop straight away
  • continue skips the rest of this round and starts the next one

while True: with a break inside is a common way to write “keep going until…”.

Python
n = 0
while True:
    n += 1
    if n == 3:
        continue
    if n > 5:
        break
    print(n)

Practise “while loops” in the game

Lesson 3

Adding things up

Running totals, counting, and looping over the letters in a word.

A running total

To add up numbers in a loop, make a variable before the loop that starts at 0. Inside the loop, add each number to it.

This is one of the most useful patterns in programming.

Python
total = 0
for n in range(1, 5):
    total += n
print(total)

Looping over text

for letter in word: goes through a string one letter at a time.

Add an if inside to count only some of them.

Python
word = "banana"
count = 0
for letter in word:
    if letter == "a":
        count += 1
print(f"{word}: {count}")

Practise “Adding things up” in the game

Recap

What Level 3 covers, in a few lines.

  • for i in range(5): runs the indented lines 5 times, with i going 0, 1, 2, 3, 4.
  • range(start, stop) counts from start up to, but not including, stop. A third number is the step: range(0, 10, 2).
  • while condition: repeats as long as the condition is true. Something inside has to change, or it never stops.
  • break leaves a loop straight away; continue skips to the next round.
  • To add things up, start a total at 0 before the loop and add to it inside. for letter in word: goes through text one letter at a time.

Now try it in Python School

Write real Python and run it right there, with a check after every step and a test at the end of each level. Free.

Start learning