UNIHIVE

Study Hub UNIPORT COS 102

COS 102 · Problem Solving

Repetition and lists

for and while loops, counters and running totals, and storing many values in a list.

Our notes

1 min read

Why loops

Loops repeat steps without writing them many times. They are where computers save the most effort.

The for loop

for i in range(1, 6):
    print(i, "squared is", i * i)

range(1, 6) gives 1, 2, 3, 4, 5 (it stops before 6).

The while loop

Repeats as long as a condition is true; use it when you don't know in advance how many times.
balance = 10000
months = 0
while balance < 20000:
    balance = balance * 1.05
    months = months + 1
print(months, "months")

Savings of ₦10,000 growing 5% a month pass ₦20,000 after 15 months (1.05 raised to 14 is about 1.98 and to 15 about 2.08).

Lists

A list holds many values in order, numbered from 0.
scores = [56, 72, 38, 90, 64]
print(scores[0]) # 56
print(len(scores)) # 5

Worked example: total, average, count of passes

scores = [56, 72, 38, 90, 64]
total = 0
passes = 0
for s in scores:
    total = total + s
    if s >= 40:
        passes = passes + 1
print("Average:", total / len(scores))
print("Passes:", passes)

Output: Average: 64.0 and Passes: 4. Check: 56 + 72 + 38 + 90 + 64 = 320 and 320 ÷ 5 = 64 ✓; only 38 fails.

Worked example: linear search

names = ["Chidi", "Amaka", "Tunde", "Ngozi"]
target = "Tunde"
found = -1
for i in range(len(names)):
    if names[i] == target:
        found = i
print("Position:", found)

Prints Position: 2 (counting from 0). If the name is missing it prints −1.

Infinite loops

A while loop whose condition never becomes false runs for ever (forgetting months = months + 1 above would not stop it, but forgetting to change balance would). Press Ctrl+C to stop a runaway program.

Exams usually ask

  • Write a loop to sum, average, count or find the largest value in a list.
  • Give the output of a loop and the final values of its variables.

Common mistake

Off-by-one errors: range(1, 10) stops at 9, and the last item of a list of n items is at position n − 1.

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

Read

Watch

We link to free material and never copy it. Every link was opened by our team before it went up; video data is a rough guide at 360p.

All COS 102 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.