Lesson 4 of 5

Loops: Repeating Work

Doing Things Again and Again

Computers are excellent at repetition. A loop runs the same block of code many times so you do not have to write it out by hand.

The for Loop

A for loop walks through a sequence of items, one at a time. The range() function produces a sequence of numbers.

for i in range(5):
    print("Count:", i)

This prints the numbers 0, 1, 2, 3, 4. Note that range(5) starts at 0 and stops before 5, giving exactly five values.

You can also loop directly over a list of items.

subjects = ["Math", "Accounting", "ICT"]
for subject in subjects:
    print(f"Studying {subject}")

The while Loop

A while loop keeps running as long as a condition stays True. Use it when you do not know in advance how many repetitions you need.

count = 1
while count <= 3:
    print("Attempt", count)
    count = count + 1

The line count = count + 1 is essential. Without it the condition would always be True and the loop would run forever — an infinite loop.

break and continue

  • break stops the loop immediately.
  • continue skips the rest of the current pass and jumps to the next one.
for n in range(1, 10):
    if n == 5:
        break          # stop entirely when n is 5
    if n % 2 == 0:
        continue       # skip even numbers
    print(n)           # prints 1, then 3

Accumulating a Result

A very common pattern is building up a total inside a loop.

total = 0
for mark in [70, 85, 90]:
    total = total + mark
print("Total marks:", total)  # 245
If your program seems frozen, you may have created an infinite loop. Always make sure the loop condition can eventually become False.
Next
How did you find this lesson?

Discussion

0
To join the discussion, comment and react, log in or create an account.

No comments yet — be the first to leave one!