Scenario: Temperatures over four days are stored in a 2D array. Each row is a day and each column is a time: Morning, Afternoon and Evening.
Data
temperatures = [
# Morning, Afternoon, Evening
[15, 22, 18], # Day 1
[14, 25, 20], # Day 2
[18, 28, 22], # Day 3
[12, 19, 15] # Day 4
]
Your tasks
- Counting — count how many readings across all days were 20 degrees or higher.
- Totalling — calculate and print the total of the temperatures on Day 3 (row index 2).
- Averaging — calculate the average Afternoon temperature across all 4 days (column index 1).
- Maximum and minimum — find the highest Afternoon temperature and the lowest Morning temperature.
💡 Try every task in your editor first. Only reveal the solution when you have had a proper go.
Solution
temperatures = [
[15, 22, 18],
[14, 25, 20],
[18, 28, 22],
[12, 19, 15]
]
# Question 1: Counting
count = 0
for row in temperatures:
for temp in row:
if temp >= 20:
count = count + 1
print("Readings of 20 or higher:", count)
# Question 2: Day 3 total
day3_total = 0
for temp in temperatures[2]:
day3_total = day3_total + temp
print("Day 3 total:", day3_total)
# Question 3: Afternoon average (column 1)
afternoon_total = 0
for r in range(len(temperatures)):
afternoon_total = afternoon_total + temperatures[r][1]
afternoon_average = afternoon_total / len(temperatures)
print("Afternoon average:", afternoon_average)
# Question 4: Max afternoon, min morning
max_afternoon = temperatures[0][1]
min_morning = temperatures[0][0]
for r in range(len(temperatures)):
if temperatures[r][1] > max_afternoon:
max_afternoon = temperatures[r][1]
if temperatures[r][0] < min_morning:
min_morning = temperatures[r][0]
print("Highest afternoon temperature:", max_afternoon)
print("Lowest morning temperature:", min_morning)
Example output:
Readings of 20 or higher: 5
Day 3 total: 68
Afternoon average: 23.5
Highest afternoon temperature: 28
Lowest morning temperature: 12