On this page
  1. Welcome
  2. Part 1 · While loops
  3. Part 2 · Lists
  4. Part 3 · Looping lists
  5. Part 4 · Counting
  6. Part 5 · Totaling
  7. Part 6 · Max and min
  8. Part 7 · Combined
  9. Common mistakes
  10. Practice
  11. Quizzes
  12. Challenges

Year 8 · Python

While loops, lists and data techniques

In Year 7 you used for loops and conditionals. This module adds while loops and one-dimensional arrays (lists in Python), then the classic techniques programmers use with data: counting, totaling, and finding the maximum and minimum. Complete this before the Pico W project.

  • Repeat code with while loops (including sentinel values)
  • Store ordered data in a list (a 1D array)
  • Access items with indexes and loop through a list
  • Use counting, totaling, max and min patterns

Part 1: While loops

A for loop is great when you know how many times to repeat. A while loop repeats as long as a condition is True.

count = 1
while count <= 5:
    print(count)
    count = count + 1
print("Done")

Output:

1 2 3 4 5 Done

Two important rules (same idea as if and for):

  1. The while line ends with a colon :
  2. The code to repeat is indented
⚠️ Something inside the loop must eventually make the condition False, or the loop never ends (an infinite loop). Here, count = count + 1 is what moves us towards finishing.

When to use while vs for

SituationBetter choiceExample
You know the number of repeatsfor with rangePrint 1 to 10
Keep going until something happenswhileAsk until the password is correct
Loop forever on purpose (devices)while TrueKeep checking a sensor on the Pico W

Sentinel values (stopping when the user says so)

A sentinel is a special value that means "stop". Here the user enters marks until they type -1:

mark = int(input("Enter a mark (-1 to stop): "))
while mark != -1:
    print("You entered", mark)
    mark = int(input("Enter a mark (-1 to stop): "))
print("Finished entering marks")
💡 Notice we ask for the first mark before the loop, then ask again at the end of the loop. That way -1 is never treated as a real mark.

Part 2: One-dimensional arrays (lists)

An array stores many values in one named structure, in order. In Python the usual 1D array is a list.

scores = [8, 5, 9, 7, 6]
print(scores)

Output:

[8, 5, 9, 7, 6]

Think of a list as a row of numbered boxes:

Index01234
Value85976
⚠️ Indexes start at 0, not 1. The first item is scores[0]. The last item here is scores[4].

Reading and changing items

scores = [8, 5, 9, 7, 6]
print(scores[0])     # 8  (first item)
print(scores[2])     # 9
scores[1] = 10       # change the second item
print(scores)        # [8, 10, 9, 7, 6]

Length of a list

Use len() to find how many items are in the list:

scores = [8, 5, 9, 7, 6]
print(len(scores))   # 5

Adding items with append

names = ["Aisha", "Ben"]
names.append("Chloe")
print(names)         # ["Aisha", "Ben", "Chloe"]

Part 3: Looping through a list

Option A: for each item

scores = [8, 5, 9, 7, 6]
for score in scores:
    print(score)

Option B: for each index

Use indexes when you need the position as well as the value:

scores = [8, 5, 9, 7, 6]
for i in range(len(scores)):
    print("Index", i, "is", scores[i])

Output:

Index 0 is 8 Index 1 is 5 Index 2 is 9 Index 3 is 7 Index 4 is 6
💡 range(len(scores)) gives 0, 1, 2, … up to one before the length. That visits every index safely.

Part 4: Technique — counting

Counting means keeping a variable that goes up by 1 whenever something matches a rule.

Pattern:

  1. Start a counter at 0
  2. Loop through the data
  3. If the item matches, add 1 to the counter
  4. After the loop, the counter is your answer
scores = [8, 5, 9, 7, 6, 9, 4]
count = 0

for score in scores:
    if score >= 7:
        count = count + 1

print(count, "scores were 7 or more")

Output:

4 scores were 7 or more

You can also count while the user types values:

count = 0
number = int(input("Enter a number (0 to stop): "))
while number != 0:
    if number % 2 == 0:
        count = count + 1
    number = int(input("Enter a number (0 to stop): "))
print("Even numbers entered:", count)

Part 5: Technique — totaling

Totaling (also called summing) means adding values into a running total.

Pattern:

  1. Start total at 0
  2. Loop through the data
  3. Add each value: total = total + value
  4. After the loop, use the total (and often the average)
scores = [8, 5, 9, 7, 6]
total = 0

for score in scores:
    total = total + score

average = total / len(scores)
print("Total:", total)
print("Average:", average)

Output:

Total: 35 Average: 7.0

Trace of the total:

Loopscoretotal after
Start–0
1st88
2nd513
3rd922
4th729
5th635

Part 6: Technique — maximum and minimum

To find the largest or smallest value, keep a "best so far" variable and update it when you see a better value.

Finding the maximum

scores = [8, 5, 9, 7, 6]
biggest = scores[0]   # start with the first item

for score in scores:
    if score > biggest:
        biggest = score

print("Highest score:", biggest)

Output:

Highest score: 9

Finding the minimum

scores = [8, 5, 9, 7, 6]
smallest = scores[0]

for score in scores:
    if score < smallest:
        smallest = score

print("Lowest score:", smallest)

Output:

Lowest score: 5
💡 Starting with scores[0] is safer than guessing a number like 0, because the real values might all be negative.
💡 Python also has max(scores) and min(scores). In this module you should practise the loop versions so you understand the technique.

Part 7: Putting the techniques together

Real programs often combine counting, totaling and max/min in one pass through the list:

scores = [8, 5, 9, 7, 6, 9, 4]

total = 0
count_high = 0
biggest = scores[0]
smallest = scores[0]

for score in scores:
    total = total + score
    if score >= 8:
        count_high = count_high + 1
    if score > biggest:
        biggest = score
    if score < smallest:
        smallest = score

print("Total:", total)
print("Average:", total / len(scores))
print("Scores of 8+:", count_high)
print("Max:", biggest)
print("Min:", smallest)

Building a list with a while loop

Collect numbers from the user, then analyse them:

numbers = []
value = int(input("Enter a number (-1 to stop): "))
while value != -1:
    numbers.append(value)
    value = int(input("Enter a number (-1 to stop): "))

if len(numbers) == 0:
    print("No numbers entered")
else:
    total = 0
    for n in numbers:
        total = total + n
    print("You entered", len(numbers), "numbers")
    print("Total:", total)
    print("Average:", total / len(numbers))

Common mistakes checklist

MistakeExampleFix
Forgetting to update the while conditionwhile x < 10: but never change xChange x inside the loop
Off-by-one with indexesUsing scores[5] on a list of length 5Last index is len(scores) - 1
Starting max/min at 0 alwaysbiggest = 0 when all values are negativeStart with scores[0]
Totaling without resettingReusing an old totalSet total = 0 before the loop
Treating the sentinel as dataAdding -1 into the totalCheck for stop before processing
Using = instead of ==while mark = -1:Use == to compare

Practice questions

Work through these in order. Solutions are hidden — try each question yourself, then click Show solution.

Section A: While loops

A1. What will this code print?

n = 3
while n > 0:
    print(n)
    n = n - 1
print("Go")

A2. Why is this an infinite loop? How would you fix it?

x = 1
while x < 5:
    print(x)

A3. Write a program that keeps asking for a password until the user types python. Then print Access granted.

Use a while loop.

A4. Write a program that asks the user for positive numbers and stops when they enter 0. Print how many numbers were entered (not counting the 0).

Section B: Lists (1D arrays)

B1. For temps = [12, 15, 9, 18], what is temps[0]? What is temps[3]? What is len(temps)?

B2. What will this code print?

colours = ["red", "green", "blue"]
colours[1] = "yellow"
colours.append("purple")
print(colours)

B3. Write a program that creates a list of five test marks entered by the user, then prints the list.

Hint: start with an empty list and use append in a loop.

B4. Write a program that prints each item in names = ["Sam", "Jia", "Omar", "Nina"] with its index, like 0: Sam.

Section C: Counting, totaling, max and min

C1. Using data = [3, 8, 2, 8, 5, 8], write a program that counts how many times 8 appears.

C2. Write a program that totals the list prices = [2.50, 1.20, 3.00, 0.80] and prints the total.

C3. Complete a trace table for this code. What is printed?

values = [4, 11, 7, 15, 9]
biggest = values[0]
for v in values:
    if v > biggest:
        biggest = v
print(biggest)

C4. Write a program that finds both the maximum and minimum of ages = [14, 12, 15, 13, 12, 16] using loops (not max()/min()).

C5. Write a program that reads integers until the user enters -1, stores them in a list, then prints the count of numbers, the total, and the average.

If no numbers were entered, print a suitable message instead of dividing by zero.

Section D: Challenge questions

D1. Rainfall. The list rain = [2, 0, 5, 0, 1, 8, 0] is rainfall in mm for 7 days. Print how many dry days (0 mm), the total rainfall, and the wettest day index (0–6).

D2. Write a program that asks for 6 race times (floats), stores them in a list, then prints the fastest time (minimum) and how many times were under 12 seconds.

D3. Quiz scores. Ask the user how many scores they want to enter (n), then read n scores into a list. Print the average, the highest score, and a count of fails (scores below 40).

Well done! You can now use while loops and lists, and apply counting, totaling, max and min. Next try the Year 8 quizzes, then the harder practice challenges (one challenge per page, with a hidden solution), then put coding into hardware with the Year 8 Pico W project.