A1. What will this code print?
n = 3
while n > 0:
print(n)
n = n - 1
print("Go")
Solution
Output:
Year 8 · Python
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.
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:
Two important rules (same idea as if and for):
while line ends with a colon :count = count + 1 is what moves us towards finishing.while vs for| Situation | Better choice | Example |
|---|---|---|
| You know the number of repeats | for with range | Print 1 to 10 |
| Keep going until something happens | while | Ask until the password is correct |
| Loop forever on purpose (devices) | while True | Keep checking a sensor on the Pico W |
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")
-1 is never treated as a real mark.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:
Think of a list as a row of numbered boxes:
| Index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Value | 8 | 5 | 9 | 7 | 6 |
scores[0]. The last item here is scores[4].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]
Use len() to find how many items are in the list:
scores = [8, 5, 9, 7, 6]
print(len(scores)) # 5
appendnames = ["Aisha", "Ben"]
names.append("Chloe")
print(names) # ["Aisha", "Ben", "Chloe"]
scores = [8, 5, 9, 7, 6]
for score in scores:
print(score)
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:
range(len(scores)) gives 0, 1, 2, … up to one before the length. That visits every index safely.Counting means keeping a variable that goes up by 1 whenever something matches a rule.
Try the interactive simulation: Counting occurrences on CompSimu.
Pattern:
0scores = [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:
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)
Totaling (also called summing) means adding values into a running total.
Try the interactive simulation: Totalling an array on CompSimu.
Pattern:
total at 0total = total + valuescores = [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:
Trace of the total:
| Loop | score | total after |
|---|---|---|
| Start | – | 0 |
| 1st | 8 | 8 |
| 2nd | 5 | 13 |
| 3rd | 9 | 22 |
| 4th | 7 | 29 |
| 5th | 6 | 35 |
To find the largest or smallest value, keep a "best so far" variable and update it when you see a better value.
Try the interactive simulation: Finding max and min on CompSimu.
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:
scores = [8, 5, 9, 7, 6]
smallest = scores[0]
for score in scores:
if score < smallest:
smallest = score
print("Lowest score:", smallest)
Output:
scores[0] is safer than guessing a number like 0, because the real values might all be negative.max(scores) and min(scores). In this module you should practise the loop versions so you understand the technique.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)
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))
| Mistake | Example | Fix |
|---|---|---|
| Forgetting to update the while condition | while x < 10: but never change x | Change x inside the loop |
| Off-by-one with indexes | Using scores[5] on a list of length 5 | Last index is len(scores) - 1 |
| Starting max/min at 0 always | biggest = 0 when all values are negative | Start with scores[0] |
| Totaling without resetting | Reusing an old total | Set total = 0 before the loop |
| Treating the sentinel as data | Adding -1 into the total | Check for stop before processing |
Using = instead of == | while mark = -1: | Use == to compare |
Work through these in order. Solutions are hidden — try each question yourself, then click Show solution.
n = 3
while n > 0:
print(n)
n = n - 1
print("Go")
Solution
Output:
x = 1
while x < 5:
print(x)
Solution
x never changes, so x < 5 stays True forever. Fix by updating x inside the loop, for example x = x + 1.
x = 1
while x < 5:
print(x)
x = x + 1
python. Then print Access granted.Use a while loop.
Solution
password = input("Enter password: ")
while password != "python":
print("Try again")
password = input("Enter password: ")
print("Access granted")
Solution
count = 0
number = int(input("Enter a positive number (0 to stop): "))
while number != 0:
count = count + 1
number = int(input("Enter a positive number (0 to stop): "))
print("Numbers entered:", count)
temps = [12, 15, 9, 18], what is temps[0]? What is temps[3]? What is len(temps)?Solution
temps[0] → 12temps[3] → 18len(temps) → 4colours = ["red", "green", "blue"]
colours[1] = "yellow"
colours.append("purple")
print(colours)
Solution
Output:
Hint: start with an empty list and use append in a loop.
Solution
marks = []
for i in range(5):
mark = int(input("Enter mark: "))
marks.append(mark)
print(marks)
names = ["Sam", "Jia", "Omar", "Nina"] with its index, like 0: Sam.Solution
names = ["Sam", "Jia", "Omar", "Nina"]
for i in range(len(names)):
print(str(i) + ":", names[i])
data = [3, 8, 2, 8, 5, 8], write a program that counts how many times 8 appears.Solution
data = [3, 8, 2, 8, 5, 8]
count = 0
for n in data:
if n == 8:
count = count + 1
print(count)
Answer: 3
prices = [2.50, 1.20, 3.00, 0.80] and prints the total.Solution
prices = [2.50, 1.20, 3.00, 0.80]
total = 0
for price in prices:
total = total + price
print(total)
Total = 7.5
values = [4, 11, 7, 15, 9]
biggest = values[0]
for v in values:
if v > biggest:
biggest = v
print(biggest)
Solution
| Loop | v | biggest after |
|---|---|---|
| Start | – | 4 |
| 1st | 4 | 4 |
| 2nd | 11 | 11 |
| 3rd | 7 | 11 |
| 4th | 15 | 15 |
| 5th | 9 | 15 |
It prints 15.
ages = [14, 12, 15, 13, 12, 16] using loops (not max()/min()).Solution
ages = [14, 12, 15, 13, 12, 16]
biggest = ages[0]
smallest = ages[0]
for age in ages:
if age > biggest:
biggest = age
if age < smallest:
smallest = age
print("Max:", biggest)
print("Min:", smallest)
-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.
Solution
numbers = []
n = int(input("Enter a number (-1 to stop): "))
while n != -1:
numbers.append(n)
n = int(input("Enter a number (-1 to stop): "))
if len(numbers) == 0:
print("No numbers entered")
else:
total = 0
for value in numbers:
total = total + value
print("Count:", len(numbers))
print("Total:", total)
print("Average:", total / len(numbers))
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).Solution
rain = [2, 0, 5, 0, 1, 8, 0]
dry_days = 0
total = 0
wettest_index = 0
for i in range(len(rain)):
total = total + rain[i]
if rain[i] == 0:
dry_days = dry_days + 1
if rain[i] > rain[wettest_index]:
wettest_index = i
print("Dry days:", dry_days)
print("Total rainfall:", total)
print("Wettest day index:", wettest_index)
Solution
times = []
for i in range(6):
t = float(input("Enter time: "))
times.append(t)
fastest = times[0]
under_12 = 0
for t in times:
if t < fastest:
fastest = t
if t < 12:
under_12 = under_12 + 1
print("Fastest:", fastest)
print("Under 12 seconds:", under_12)
n), then read n scores into a list. Print the average, the highest score, and a count of fails (scores below 40).Solution
n = int(input("How many scores? "))
scores = []
for i in range(n):
scores.append(int(input("Enter score: ")))
total = 0
highest = scores[0]
fails = 0
for score in scores:
total = total + score
if score > highest:
highest = score
if score < 40:
fails = fails + 1
print("Average:", total / n)
print("Highest:", highest)
print("Fails:", fails)