Loops
Repeat work with for and while, use range, and avoid off-by-one mistakes.
18 min
A loop repeats a block. Python has two kinds.
for letter in "cat":
print(letter) # c, then a, then t
for n in range(3):
print(n) # 0, 1, 2range(stop) counts from 0 up to but not including stop. range(start, stop) and range(start, stop, step) give more control: range(1, 6) is 1,2,3,4,5 and range(10, 0, -3) is 10,7,4,1.
count = 3
while count > 0:
print(count)
count = count - 1
print("Liftoff")A while loop must change something that eventually makes the condition false. If not, it runs forever (an infinite loop). Use for when you know what you are looping over, while when you do not know how many rounds you need.
The most common loop pattern is to start with a value, then update it each round:
total = 0
for n in [4, 8, 15]:
total += n # same as total = total + n
print(total) # 27break leaves a loop early; continue skips to the next round.
The accumulator pattern: set up, repeat, then use the result.
Read a whole number n from input and print the sum of every whole number from 1 to n, using a loop.
For 5 print 15 (1+2+3+4+5).
Your code must satisfy
- five
- one
- hundred
n = int(input())
total = 0first_squares(n) should return the first n square numbers as a list: first_squares(4) is [1, 4, 9, 16]. Something is off by one.
What it does now
first_squares(4) returns [0, 1, 4, 9]: it starts at 0 and stops one square too early.
Your code must satisfy
- first_squares(4)→[1,4,9,16]four
- first_squares(1)→[1]one
- first_squares(0)→[]zero
- first_squares(6)→[1,4,9,16,25,36]six
def first_squares(n):
squares = []
for i in range(n):
squares.append(i * i)
return squares“`range(5)` gives the numbers 1 to 5.”
In everyday counting, "five" means one through five.
What is actually true
range(5) gives 0, 1, 2, 3, 4: five numbers, starting at zero, never including the stop value. For 1 to 5, write range(1, 6).
How to catch yourself
When a loop is one short or one long, print the range with `list(range(...))`.
Before you run a loop
forrepeats once per item;range(a, b)runs fromaup to but not includingb.whilerepeats while a condition is true, so the body must move it towards false.- The accumulator pattern (start, update in the loop, use after) covers sums, counts and lists.
- Off-by-one errors are the classic loop bug: test with 0 and 1 items.
Trace the loops.
What does list(range(2, 7)) give?
- A[2, 3, 4, 5, 6, 7]
- B[2, 3, 4, 5, 6]
- C[3, 4, 5, 6, 7]
- D[2, 7]
How many times does for i in range(4): run its body?
What does total hold at the end? total = 0, then for n in [2, 4, 6]: total += n
Which loop never ends?
- A`for i in range(3): print(i)`
- B`n = 3` / `while n > 0: print(n)`
- C`while False: print(1)`
- D`for c in "": print(c)`
Put these in the order a sum loop runs them.
- AAdd it to total
- BPrint total after the loop ends
- CSet total to 0
- DTake the next number
Practise this lesson, not just read it
In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of Python for Complete Beginners is planned around your week. Free.