Learning outcomes
By the end of this lesson you should be able to: repeat a block while a condition holds using while; iterate over a special collection with for; stop or skip ahead inside a loop with break and continue; and write the accumulate-a-total pattern that appears constantly in real programs.
Prerequisites
Lesson 4 (Conditions). You need if/elif/else and the boolean operators, because a loop's repetition is governed by a condition of exactly the kind you just learned to write — and because break and continue make decisions inside each pass.
The big idea
Until now, every program you wrote had a fixed number of steps. That is a significant limit. If you wanted to count to a thousand, or read every line of a file, or sum a list of unknown length, you could not write out each step by hand. A loop removes the limit. You describe the pattern once, and tell the computer how many times — or under what condition — to repeat it.
Why this matters before the syntax
There are two loop kinds in Python, and choosing between them is the first decision. A while loop keeps going as long as some condition is True — you do not know in advance how many passes there will be, you just know when to stop. A for loop marches through a known sequence — you usually know exactly how many items there are. Beginners reach for while as the default and then get stuck on the infinite loop; the habit worth building is to use for when you can, because it is harder to make a for loop run forever.
The second thing to know is the accumulate pattern, which is the heart of nearly everything to come. Almost every loop you write will do one of two things: collect or accumulate. Collect means building up a new value each pass (a running total, a list of results). Accumulate means adding to something you started before the loop. Either way you must initialise an accumulator before the loop and then update it inside — two separate steps, and forgetting the first is a classic bug.
Third: break and continue are exits, not the loop itself. break stops the loop immediately and jumps past it; continue skips the rest of the current pass and goes to the next one. They are sometimes overused. If you find yourself using break in every loop, there is usually a cleaner condition. But they are genuinely useful for the classic pattern of finding something and stopping the moment you find it.
Worked example 1: the while loop
Count from 0 to 4. The loop runs while n is less than 5, printing and then increasing n each pass, so it stops once n reaches 5.
n = 0
while n < 5:
print(n)
n = n + 10
1
2
3
4Three parts make this work. There is an initialisation before the loop — n = 0 — so the condition has a value to test the first time. There is the condition itself, n < 5, which is re-checked at the start of every pass. And there is an update inside, n = n + 1, so that the condition eventually becomes False. Remove the update and the loop never ends — the condition stays True forever. Remove the initialisation and n does not exist when the loop first checks it.
Worked example 2: the for loop
The same counting, done with for. Here the sequence is supplied by range, so you do not manage your own counter.
for i in range(3):
print(i)0
1
2range(3) is a sequence of three numbers: 0, 1 and 2. It stops before 3, which surprises people who expect it to include the last number. The for loop takes each value in the sequence, assigns it to the variable i, and runs the indented block. This is the loop you will use most — it reads naturally, it cannot accidentally miss its update, and it is very hard to make infinite.
Worked example 3: stopping early with break
Search the numbers 0 to 9 and stop the moment you reach 3. The loop looks like it should go to 9, but break cuts it off.
for i in range(10):
if i == 3:
break
print(i)0
1
2Notice the print comes after the if. When i reaches 3, the condition i == 3 is True, so break fires — it leaves the loop immediately without running the rest of that pass, which is the print. That is why 3 is not printed. This is the find-and-stop pattern: you test inside the loop, and the moment you find what you want, you break. If the print had gone before the if, 3 would have been printed first. Order matters.
Worked example 4: skipping one with continue
Print the numbers 0 to 4 but skip 2. continue jumps to the next pass without executing the lines after it.
for i in range(5):
if i == 2:
continue
print(i)0
1
3
4continue only skips the rest of the current iteration; it does not end the loop. When i is 2, the if matches and continue sends control back to the top of the loop with the next value, 3. Everything after the continue in that pass — the print — is skipped for 2 only. The loop still runs to completion for every other value. Where break is an exit, continue is a skip.
Worked example 5: the accumulate pattern
Sum the numbers 1 to 5. You start a total before the loop and add each number inside it.
total = 0
for i in range(1, 6):
total = total + i
print("sum:", total)sum: 15This is the pattern that appears in every data program you will write from now on. Before the loop, total = 0 initialises the accumulator — this is easy to forget, and if you do, total does not exist when the loop first tries to add to it. Inside the loop, total = total + i reads the current total, adds the new value, and stores the result back. Each pass the total grows. This same skeleton, with slight changes, is what counts words, finds maximums, and builds almost every summary in the PY4E course.
Common mistakes
Watch outAn infinite loop. If the condition never becomes False — usually because the update is missing or inside an if — the loop runs forever. Make sure the body changes something that affects the condition.
Watch outForgetting to initialise an accumulator before the loop. If you write total = total + i inside a loop without a total = 0 before it, Python raises a NameError the first time.
Watch outOff-by-one in range. range(5) gives 0..4, not 0..5. To include the last number, range(1, 6) — the stop value is exclusive.
Watch outUsing while when a for would be safer. A for loop knows when to stop and cannot easily miss its update, so reach for it whenever you are stepping through a known sequence.
Check your understanding
Why does the while loop below never end? n = 0 while n < 5: print(n)
What values does range(3) visit, and which value is excluded?
In the accumulate pattern, why must the accumulator be set before the loop?
Multiple choice
Which loop repeats while a condition holds, and may not know how many times in advance?
What does break do inside a loop?
What is the output of for i in range(4): print(i)?
Which code produces an infinite loop?
A loop prints all values but must skip 4. Which keyword does it?
Which is the accumulate-total skeleton in the right order?
To sum the numbers from 1 to 5 inclusive, what range do you use?
Why does placing the print after the if matter in a break loop?
Summary and next
A loop repeats a block: while repeats while a condition holds, for steps through a sequence. break exits, continue skips a pass, and the accumulate pattern — initialise a total, then add each value inside — is the skeleton behind nearly every data program. Prefer for when you know the sequence, and always make sure something in a while body changes its condition.
Next: logic & debugging basics. Lesson 5 gave you repetition; the next lesson steps back and shows you how to read a tricky loop and find the errors when one does not do what you meant — the skill that turns a writer of small loops into someone who can untangle them.