Repeating things with loops
Computers are good at doing the same thing over and over without getting bored. Loops are how you ask.
The problem loops solve
Say you want to count to five:
print(1)
print(2)
print(3)
print(4)
print(5)
1 2 3 4 5
That works. Now count to a thousand. You see the problem.
for and range
for number in range(1, 6):
print(number)
1 2 3 4 5
Five lines became two, and counting to a thousand is now a one-character change.
Read it as English: for each number in this range, print it. The variable
number is created by the loop and holds a different value each time round.
Notice the colon and the indent — the same grammar as if. Everything indented
under the for is the part that repeats.
range is exclusive at the top
This is the one thing about range() that catches everyone:
for n in range(1, 4):
print(n)
1 2 3
range(1, 4) gives 1, 2, 3 — it stops before 4. The first number is
included, the last is not.
With one argument it starts at zero:
for n in range(3):
print(n)
0 1 2
range(3) means "three times", giving 0, 1, 2. This looks strange for about a
week and then feels normal, because most counting in programming starts at zero.
Doing something useful each time
The loop variable is an ordinary variable — use it:
for n in range(1, 6):
print(f"{n} squared is {n * n}")
1 squared is 1 2 squared is 4 3 squared is 9 4 squared is 16 5 squared is 25
Building up an answer
A common pattern: start with a total, add to it each time round.
total = 0
for n in range(1, 11):
total = total + n
print(f"The numbers 1 to 10 add up to {total}")
The numbers 1 to 10 add up to 55
The line that matters is total = total + n — the same "take the old value,
make a new one, store it back" idea from the variables lesson. Note that
total = 0 sits outside the loop. Put it inside and you would reset it to
zero every single time round, and the answer would be 10.
Python has a shorthand for this, and you will see it everywhere:
total = 0
for n in range(1, 11):
total += n
print(total)
55
total += n means exactly total = total + n.
while: loop until something changes
for repeats a known number of times. while repeats as long as something
stays true:
countdown = 3
while countdown > 0:
print(countdown)
countdown -= 1
print("Go!")
3 2 1 Go!
Each time round, Python checks the condition. When countdown reaches 0 the
condition is false and the loop stops.
The trap: loops that never end
countdown = 3
while countdown > 0:
print(countdown)
Nothing changes countdown, so countdown > 0 is true forever and this prints
3 until you close the tab. Do not run that one — it will hang this page.
Whenever you write a while, ask yourself immediately: what, inside this loop,
will eventually make the condition false? If you cannot answer, you have an
infinite loop.
This is the main reason to prefer for when you know how many times to repeat.
A for loop cannot run forever.
Stopping early
break leaves a loop immediately:
for n in range(1, 100):
if n * n > 50:
print(f"{n} is the first number whose square passes 50")
break
8 is the first number whose square passes 50
Without break this would keep going to 99 pointlessly. With it, the loop stops
the moment the job is done.
Prefer learning with a teacher?
WasiLearn Academy runs small-group classes covering this material, online and in Karachi.
See the classes