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 for loop that prints every name in names.

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 for and range() 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 while loop to count down: print count, then take 1 away, while count is more than 0.

  • After the loop (not indented), print Liftoff!.

break and continue

Two words let you steer a loop:

  • continue skips the rest of this turn and moves to the next item
  • break stops 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. Use continue to skip numbers below 0.

  • Use break to 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 prices and add each price to total.

  • 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 scores and print 55: fail or 82: pass style lines.

  • Count the passes in passed and print 3 passed after the loop.

More in Python Control Flow & Lists

Previous: Lists · Next: Functions