Part 2: Core Programming Concepts
Part 2: Core Programming Concepts — read through each chapter in order. Diagrams, tables and worked examples included.
5. Loops & Iteration
Repeating work without repeating yourself
A loop runs a block of code again and again. This is how programs process every item in a list, keep asking until input is valid, or count from 1 to a million without you typing a million lines. Running the body once is called an iteration.
The while loop
A while loop repeats as long as a condition stays true. It checks the condition, runs the body, then checks again. Use it when you do not know in advance how many times you will repeat — for example, "keep going until the user types 'quit'."
count = 1
while count <= 3:
print("Hello", count)
count = count + 1 # move toward the exit!
print("Done")
Line by line: count starts at 1, the condition 1 <= 3 is true so the body prints and increments to 2, then 3, then 4. At 4 <= 3 the condition is false and the loop ends. The variable that drives the loop is the loop counter.
Infinite loops
If the condition never becomes false, the loop runs forever — an infinite loop. The usual cause is forgetting to change the counter. Always make sure something inside the body moves you toward the exit condition.
# BUG: count never changes, so this never stops
count = 1
while count <= 3:
print("stuck") # prints forever
The for loop
A for loop is built for a known number of repetitions or for walking through every item in a collection. It bundles the setup, condition and update into one tidy line, which makes "off-by-one" mistakes rarer.
for i in range(1, 4): # i takes 1, then 2, then 3
print("Hello", i)
for letter in "cat": # iterate over each character
print(letter) # c, a, t
for vs while
| Aspect | for loop | while loop |
|---|---|---|
| Best when | You know the count, or iterate a collection | You repeat until a condition changes |
| Counter | Managed automatically | You manage it by hand |
| Infinite-loop risk | Lower | Higher (easy to forget the update) |
| Typical use | "for each student, print the name" | "while not logged in, keep asking" |
break and continue
Two statements fine-tune a loop. break exits the loop immediately. continue skips the rest of the current iteration and jumps to the next one. Use them sparingly — a clear condition is usually better than a loop peppered with jumps.
for n in range(1, 100):
if n == 5:
break # stop entirely at 5
if n % 2 == 0:
continue # skip even numbers
print(n) # prints 1, 3
Key idea: loops repeat work; for suits a known number of steps, while suits "until something changes," and every loop must be able to end.