OpenSesame
Rapunzel Code Editor
DataMatrix
Support forum
Python Tutorials
MindProbe
Python videos

Loops: for and while

Loops are a way to repeat blocks of code. Loops are a crucial part of programming, so let's see how they work!

In this chapter, you will learn

  • What a for loop is
  • What a while loop is
  • How to use the continue keyword
  • How to use the break keyword
  • About useful functions for working with loops

Test yourself

  • Seven interactive mini exercises
  • Two review exercises

The for loop

A for loop executes a code block for each element in an iterable, such as a list, tuple, or set. Analogous to the if statement, the for statement ends with a colon, and the to-be-looped code block is defined by indentation:

prime_numbers = [1, 3, 5, 7, 11]
for prime in prime_numbers:
    # This is inside the loop because it is indented
    print(prime)
# This is after the loop because it is no longer indented
print('Done!')

Output:

1
3
5
7
11
Done!

If you iterate (loop) through a dict, you iterate through its keys. To iterate through the keys and the values at the same time, you can use dict.items() function, which returns an iterable of (key, value) tuples.

ages = {
    'Jay-Z': 52,          # and counting
    'Emanuel Macron': 44  # and counting
}
for name, age in ages.items():
    print(f'{name} is {age} years old')

Output:

Jay-Z is 52 years old
Emanuel Macron is 44 years old

Mini exercise

You can also loop through a str, in which case you get individual characters as if you were looping through a list of characters. Use a for loop through loop through a str with the first five letters of the alphabet. Print out each character on a separate line. After the loop, print out 'Done!'

The while loop

A while loop executes a code block until a particular condition is no longer True.

user_input = ''
while user_input != 'quit':
    user_input = input('>>> ')
    print(f'The user said: {user_input}')
print('Quitting ...')

Output:

>>> Hello!
The user said: Hello!
>>> quit
The user said: quit
Quitting ...

Mini exercise

Create a simple calculator for additions! Repeatedly ask the user to enter numbers. Each time that the user provides input, this input is first converted to float and then added to a running total (which should start from 0). When the user enters 'add', the loop stops and the running total is printed out.

When running the code, enter '3', '2', '1', and 'add' to solve the exercise.

continue: abort one iteration

The continue statement, which you can use in for and while loops (but nowhere else), aborts a single iteration of a loop, and continues with the next iteration. To give an example, you can use continue to skip all cities that are not capitals:

cities = ['Berlin', 'São Paulo', 'Tokyo', 'New York']
capitals = ['Berlin', 'Tokyo']
for city in cities:
  # If the current city is not a capital, continue with the next city
  if city not in capitals:
    continue
  print(f'{city} is a capital')

Output:

Berlin is a capital
Tokyo is a capital

Mini exercise

Loop through the list of four cities above. Use continue to ignore cities that have a space in the name. Print out the other city names. (Tip: You can use in to check whether one string is a substring of another string.)

break: abort a loop

The break statement is similar to the continue statement, but aborts the loop entirely, rather than just aborting the current iteration. To give an example, you can use break to print out all prime numbers below 10.

for prime in prime_numbers:
  # Abort the loop when we reach a number that is 10 or higher
  if prime >= 10:
    break
  print(prime)

Output:

1
3
5
7

Mini exercise

Loop through the list of four cities above. Print out the name of each city. Use break to stop after Tokyo.

Useful functions

range(): iterate through a range of values

range() corresponds to a range of numbers. The simplest and most common use case is to specify only a stop value, which is exclusive (i.e. range(3) does not include 3!):

for i in range(3):
  print(i)

Output:

0
1
2

However, you can also specify a start value and a step size (negative step sizes allow you to count backwards):

from_value = 1
to_value = 4
step_size = 2
for i in range(from_value, to_value, step_size):
  print(i)

Output:

1
3

Mini exercise

Use range() to count down from 5 to 1, printing each number on a separate line. After the loop, print 'Go!'.

zip(): iterate through multiple iterables

zip() takes one or more iterables, and returns a zipped iterable in which elements from the original iterables are paired. This allows you to iterate through multiple iterables at the same time. The zipped iterable is as long as the shortest of the original iterables.

# Source: https://en.wikipedia.org/wiki/List_of_best-selling_music_artists
artists = 'The Beatles', 'Elvis Presley', 'Michael Jackson', 'Madonna'
sales = 600e6, 600e6, 350e6, 300e6
for artist, sold in zip(artists, sales):
  print(f'{artist} sold {sold} records'.format(artist, sold))

Output:

The Beatles sold 600000000.0 records
Elvis Presley sold 600000000.0 records
Michael Jackson sold 350000000.0 records
Madonna sold 300000000.0 records

Mini exercise

Use one range() to count down from 0 to 4, and another range() to count up from 4 to 0. Use zip() to loop through both ranges together. Print each pair of numbers out on a separate line in this format: '0 4', etc.

enumerate(): iterate and count

enumerate() takes an iterable, and returns another iterable in which each element is paired with a counter variable.

cities = ['Berlin', 'São Paulo', 'Tokyo', 'New York']
for i, city in enumerate(cities):
  print(f'{i}: {city}')

Output:

0: Berlin
1: São Paulo
2: Tokyo
3: New York

Mini exercise

Use range() to count down from 4 to 0. Use enumerate() to create another counter that goes for 0 to 4. Print each pair of numbers out on a separate line in this format: '0 4', etc. (I.e. the result is the same as for the previous mini exercise, but the implementation is different.)

Review exercises

Fibonacci

Calculate the Fibonacci series up to 1,000. Print out each Fibonacci number including its position in the series. Like so:

0: 1
1: 1
2: 2
3: 3
4: 5
etc.

This exercise is not checked automatically, because there are several possible solutions. Click here to see one solution!

Best-selling artists

Do the following until the user enters quit:

  • Ask the name of an artist
  • Look up the number of sales of this artist in a dict
  • Print out the result if the number of sales are known
  • If the number of sales are unknown, ask the user to enter the number of sales, and update the dict accordingly

This exercise is not checked automatically, because there are several possible solutions. Click here to see one solution!

You're done with this section!

Continue with Functions >>