All 2.1 24 min read 10 question quiz 19 exam marks

Loops: for and while

Repetition done properly, including nested loops, break and continue, and how to avoid the infinite loop that eats your afternoon.

for loops

A for loop repeats once for each item in a collection.

Python
for i in range(5):
    print(i)          # 0 1 2 3 4

range

Python
range(5)          # 0, 1, 2, 3, 4
range(2, 6)       # 2, 3, 4, 5
range(0, 10, 2)   # 0, 2, 4, 6, 8
range(10, 0, -1)  # 10, 9, 8 ... 1
range never includes the end value

range(1, 6) gives 1 to 5. This is the source of most off by one errors.

Looping over other things

Python
for name in ["Aisha", "Ben", "Chloe"]:
    print("Hello,", name)

for letter in "Python":
    print(letter)

for index, name in enumerate(["a", "b", "c"]):
    print(index, name)      # 0 a, 1 b, 2 c

Nested loops

Python
for row in range(3):
    for col in range(4):
        print("*", end=" ")
    print()

The inner loop completes fully for every single iteration of the outer loop, so this prints twelve stars in three rows of four.

for loops count; while loops wait for a conditionTwo kinds of loop. A for loop repeats a set number of times. The code for lap in range of five prints Lap and the lap number, and the picture shows it as a running track with five flags numbered 0 to 4: range of five counts from 0 up to 4, so there are five laps and the value 5 is never reached. A while loop repeats until a condition becomes False. Starting with battery equal to 3, the loop checks battery greater than 0, which is True, so it takes one off the battery and goes round again, checking before every go. At battery 0 the condition is False and the loop stops. If nothing inside the loop ever changes the battery, the condition would stay True for ever, which is an infinite loop.for: repeat a set number of timesfor.py1for lap in range(5):2    print("Lap", lap)outputLap 0 Lap 1 Lap 2 Lap 3 Lap 401234range(5) counts 0, 1, 2, 3, 4: five laps, never 5lap starts at 0, finishes at 4while: repeat until a condition is Falsewhile.py1battery = 32while battery > 0:3    battery = battery - 1battery = 33 > 0 Truebattery = 22 > 0 Truebattery = 11 > 0 Truebattery = 00 > 0 Falsestopsif battery never changed, the loop would never stop12
  1. for repeats a set number of times. range(5) gives 0, 1, 2, 3, 4: five laps.
  2. while repeats until its condition is False, checked before every go round.
Use for when you know how many times. Use while when you only know when to stop.

while loops

A while loop repeats for as long as a condition is true. Use it when you do not know how many repetitions are needed.

Python
total = 0
number = int(input("Enter a number, 0 to stop: "))

while number != 0:
    total += number
    number = int(input("Enter a number, 0 to stop: "))

print("Total:", total)

Infinite loops

Python
count = 0
while count < 10:
    print(count)      # count never changes, so this never ends

The fix is count += 1 inside the loop. Always check that something inside the loop changes the value being tested.

Press Ctrl and C to stop a runaway program.

break and continue

Python
while True:
    command = input("Command: ")
    if command == "quit":
        break             # leave the loop immediately
    if command == "":
        continue          # skip the rest of this iteration
    print("You typed", command)

while True with a break is a common and readable pattern for menus and validation.

Choosing a loop

Known number of repetitions, or looping over a collection, means for. Unknown number, depending on something that happens while running, means while.

A for loop that counts, a while loop that waits for a condition, and an infinite loopTwo kinds of loop. A for loop is used when you know how many times: for i in range 5 runs five times with i taking 0, 1, 2, 3 and 4, and then ends by itself. A while loop repeats until something changes: while guess is not cat, ask again, and when the guess is cat it carries on. The number of laps is not known in advance. The classic bug is the infinite loop. With n equal to 5 and while n greater than 0 printing n, if the line that reduces n is forgotten then n never changes, n greater than 0 is always true and the loop never stops. Make sure something inside the loop changes the condition.for: you know how many times1for i in range(5):    print('lap', i)01234i takes 0, 1, 2, 3, 4 and then the loop ends by itselffive laps, counted for youwhile: repeat until something changes2guess = ''while guess != 'cat':    guess = input('Guess? ')print('Correct!')dog!=Trueask againbird!=Trueask againcat!=Falsecarry onchecked every time round, before the body runsThe classic bug: an infinite loop3n = 5while n > 0:    print(n)    # forgot: n = n - 15n never changes, so n > 0 is always trueand the loop never stops: 5, 5, 5, 5 ...make sure something inside the loopchanges the condition
  1. for repeats a counted number of times and stops by itself.
  2. while checks a condition each time and repeats until it is false.
  3. If nothing inside the loop changes the condition, the loop never stops.
Use for when you know the count, and while when you are waiting for something to happen.

Loops in practice

Running totals and counters

Python
numbers = [4, 8, 15, 16, 23, 42]

total = 0
count_over_10 = 0

for n in numbers:
    total += n
    if n > 10:
        count_over_10 += 1

print("Total:", total)
print("Average:", total / len(numbers))
print("Over ten:", count_over_10)

Finding a maximum

Python
highest = numbers[0]        # start from the first item, never from 0
for n in numbers:
    if n > highest:
        highest = n
print("Highest:", highest)
Never initialise a maximum to 0

If every value is negative, nothing is ever greater than 0 and the answer will be wrong. Start from the first element.

Validation

Python
while True:
    entry = input("Enter a mark between 0 and 100: ")
    if entry.isdigit() and 0 <= int(entry) <= 100:
        mark = int(entry)
        break
    print("That is not a valid mark.")

Building a times table

Python
number = int(input("Which table? "))
for i in range(1, 13):
    print(number, "x", i, "=", number * i)

A simple menu

Python
while True:
    print("\n1. Add   2. View   3. Quit")
    choice = input("Choose: ")

    if choice == "1":
        print("Adding...")
    elif choice == "2":
        print("Viewing...")
    elif choice == "3":
        print("Goodbye")
        break
    else:
        print("Please choose 1, 2 or 3.")

Key terms you must be able to define

for loop
A loop that repeats once for each item in a collection or range.
while loop
A loop that repeats for as long as its condition remains true.
range()
A function producing a sequence of numbers for a for loop to work through.
Nested loop
A loop placed inside another loop.
Infinite loop
A loop whose condition never becomes false, so it never ends.
break
A statement that leaves a loop immediately.
continue
A statement that skips the rest of the current iteration and starts the next.
Iteration
One single pass through the body of a loop.

Flashcards

Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.

Definefor loop
AnswerA loop that repeats once for each item in a collection or range.
Definewhile loop
AnswerA loop that repeats for as long as its condition remains true.
Definerange()
AnswerA function producing a sequence of numbers for a for loop to work through.
DefineNested loop
AnswerA loop placed inside another loop.
DefineInfinite loop
AnswerA loop whose condition never becomes false, so it never ends.
Definebreak
AnswerA statement that leaves a loop immediately.
Definecontinue
AnswerA statement that skips the rest of the current iteration and starts the next.
DefineIteration
AnswerOne single pass through the body of a loop.

Reach the top grade on this topic

  • Choose for or while correctly and be able to justify the choice
  • Write a validation loop that keeps asking until the input is acceptable
  • Trace a nested loop and state exactly how many times the inner body runs
  • Initialise a maximum from the first element of the data, never from zero
  • Check every while loop for something that changes the condition

Mistakes that cost marks here

Avoid these
  • Assuming range(5) includes 5.
  • Writing a while loop where nothing inside changes the condition.
  • Initialising a maximum to 0 when the data could be negative.
  • Using a for loop when the number of repetitions is not known in advance.
  • Putting code that should run once inside the loop, so it runs every time.
Fun fact

A nested loop with 1000 iterations on each level runs its inner body one million times. This is why an algorithm that seems fine on ten items can freeze completely on ten thousand.

Knowledge check

0 of 10 answered
1How many times does for i in range(6) repeat?
2What does range(2, 8) produce?
3Which loop should be used when the number of repetitions is unknown?
4What causes an infinite loop?
5What does break do?
6In a nested loop where the outer runs 5 times and the inner runs 3, how many times does the inner body run?
7Why should a maximum be initialised to the first element rather than 0?
8What does continue do?
9What does for letter in "cat" loop over?
10What does enumerate() give you?
Score 0 / 10

Exam-style questions

Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.

19 marks
1State the difference between a for loop and a while loop and give one situation for each.4 marks
State

Mark scheme0 / 4
  • LA for loop repeats a known number of times or over a collection
  • LSituation such as processing every item in a list
  • LA while loop repeats while a condition is true
  • LSituation such as validating input until it is correct
Model answer

A for loop repeats a known number of times, or once for each item in a collection, so the number of iterations is decided before the loop begins. It would be used to work through every mark in a list of 30 students, because the number of repetitions is known from the length of the list. A while loop repeats for as long as its condition remains true, so the number of iterations is not known in advance and depends on what happens while the program is running. It would be used to keep asking a user to enter a valid password until they get it right, since there is no way to know how many attempts they will need.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2Write a program that keeps asking the user for numbers until they enter -1, then prints how many numbers were entered and their total.5 marks
Write

Mark scheme0 / 5
  • LInitialises a total and a counter
  • LUses a while loop
  • LReads and converts input inside the loop
  • LStops when -1 is entered without counting it
  • LPrints the count and total after the loop
Model answer

total = 0 count = 0 number = int(input("Enter a number, -1 to finish: ")) while number != -1: total += number count += 1 number = int(input("Enter a number, -1 to finish: ")) print("You entered", count, "numbers") print("Their total is", total) The first number is read before the loop so the condition has something to test. The loop continues while the number is not -1, adding to the total and increasing the counter each time before reading the next value. Because the read happens at the end of the loop body, the -1 that ends the loop is never counted or added.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3Explain what causes an infinite loop and how to prevent one.3 marks
Explain

Mark scheme0 / 3
  • LThe condition never becomes false
  • LBecause nothing inside the loop changes the value being tested
  • LPrevent it by ensuring the loop body updates the variable in the condition
Model answer

An infinite loop happens when the condition a while loop tests never becomes false, so the loop has no way to end. This is almost always because nothing inside the loop body changes the value that the condition depends on, for example writing while count is less than 10 but never increasing count. It can also happen when the change moves the value in the wrong direction. To prevent it, always check that the loop body contains a statement that alters the variable in the condition, and that it alters it in a direction that will eventually make the condition false.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4A program has a loop inside another loop. The outer loop runs 4 times and the inner loop runs 6 times. State how many times the inner loop body executes in total and explain why.3 marks
State

Mark scheme0 / 3
  • LThe inner body runs 24 times
  • LThe inner loop completes fully for each outer iteration
  • LSo the totals are multiplied together
Model answer

The inner loop body executes 24 times in total. Each time the outer loop runs one iteration, the inner loop starts from the beginning and completes all six of its own iterations before control returns to the outer loop. Since the outer loop repeats four times, the inner body runs six times on each of those four occasions, and 4 multiplied by 6 gives 24. This multiplication is why nested loops become expensive very quickly on large amounts of data.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5Write a program that finds and prints the largest number in the list [12, -5, 33, 8, -47, 21] without using the max function.4 marks
Write

Mark scheme0 / 4
  • LInitialises the largest to the first element of the list
  • LLoops through every item in the list
  • LCompares each item with the current largest
  • LUpdates the largest when a bigger value is found and prints the result
Model answer

numbers = [12, -5, 33, 8, -47, 21] largest = numbers[0] for n in numbers: if n > largest: largest = n print("The largest number is", largest) The variable largest is initialised to the first element of the list rather than to 0, which matters because the list contains negative numbers and initialising to 0 would give a wrong answer if every value were negative. The loop then compares each value with the current largest and replaces it whenever a bigger one is found, so after the loop finishes largest holds the maximum.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 19