Loops
Programming Languages · Python Control Flow & Lists · 12 min
Repeat code without copying it: for loops, range, while, break and continue.
for each item
A for loop runs the same code once for each item in a list. Each time round, the loop variable holds the next item:
for pet in ["cat", "dog"]:
print(pet)
Like if, the line ends with a colon and the code inside is indented.
Write a
forloop that prints every name innames.
Counting with range
range() makes a run of numbers to loop over. It stops before the last number:
for i in range(3):
print(i) # 0, 1, 2
for i in range(1, 4):
print(i) # 1, 2, 3
Use
forandrange()to print the numbers 1 to 5.
while loops
A while loop keeps going as long as its condition is True. Change something inside the loop, or it will run forever!
n = 1
while n <= 3:
print(n)
n = n + 1
Use a
whileloop to count down: printcount, then take 1 away, whilecountis more than 0.After the loop (not indented), print
Liftoff!.
break and continue
Two words let you steer a loop:
continueskips the rest of this turn and moves to the next itembreakstops the loop completely
for n in [1, 2, 3, 4]:
if n == 2:
continue # skip 2
if n == 4:
break # stop at 4
print(n) # 1, 3
Loop over
nums. Usecontinueto skip numbers below 0.Use
breakto stop when you reach 0. Print every number that's left.
A running total
A common trick: start a variable at 0 before the loop, then add to it each time round.
total = 0
for n in [1, 2, 3]:
total = total + n
print(total) # 6
total += n is a shorter way to write total = total + n.
Loop over
pricesand add each price tototal.After the loop, print
total.
Put it together: exam results
Go through the exam scores. A score of 60 or more is a pass. Print a line for each score, then count how many passed.
Loop over
scoresand print55: failor82: passstyle lines.Count the passes in
passedand print3 passedafter the loop.