Loops#

One major motivation for making computer programs is to automate tasks, and making the computer do our work for us. Loops are powerful tools for processing large amounts of data automatically.

Loops are the standard way of processing lists, among other things. We could access all the elements in a list manually:

judges = ['Anne Grøstad', 'Ivana Jelić', 'Jovan Ilievski', 'Lətif Hüseynov',
          'Mārtiņš Mits', 'Stéphanie Mourou-Vikström', 'Síofra O’Leary', 'Victor Soloveytchik']
print(judges[0])
print(judges[1])
print(judges[2])
# ...
Anne Grøstad
Ivana Jelić
Jovan Ilievski

But this kind of manual repetition is both tedious and error-prone, especially for long lists. Instead, we should get the computer to do the work with a for loop. This is called iterating over the list.

for judge in judges:
    print(judge)
Anne Grøstad
Ivana Jelić
Jovan Ilievski
Lətif Hüseynov
Mārtiņš Mits
Stéphanie Mourou-Vikström
Síofra O’Leary
Victor Soloveytchik

When the loop executes, the loop variable is created and bound to each list item in turn. In this case, the loop variable is judge.

Visualizing Loops#

We can visualize the execution of a loop. For this illustration we use a shorter list:

sentence = ['a', 'short', 'list']
print('Iterating over the sentence:')
for word in sentence:
    # loop starts (indentation)
    print(word)
    # loop/indentation ends
print('Done')
Iterating over the sentence:
a
short
list
Done

The animation below shows the steps the computer performs when this code executes. The box labeled word shows the loop variable that changes for each iteration.

Nested Loops#

We can use nested loops to loop over nested lists:

defendants = [['QC Leisure', 'SR Leisure Ltd', 'AV Station plc', 'Houghton'],
              ['Media Protection Services Ltd']]

for group in defendants:
    print('Listing group:')
    for defendant in group:
        print(defendant)
Listing group:
QC Leisure
SR Leisure Ltd
AV Station plc
Houghton
Listing group:
Media Protection Services Ltd

Range#

Sometimes we need to repeat an action a fixed number of times. We can do this by looping over a range of numbers with the function range().

print('Writ of summons:')
for number in range(10):
    print('Prayers for relief', number)
Writ of summons:
Prayers for relief 0
Prayers for relief 1
Prayers for relief 2
Prayers for relief 3
Prayers for relief 4
Prayers for relief 5
Prayers for relief 6
Prayers for relief 7
Prayers for relief 8
Prayers for relief 9

While Loops#

We have seen that for loops iterate over a sequence. We can also keep doing something as long as some condition is true, i.e. while the condition is true. For this, we use a while expression.

For example, we could make a system for collecting client information. There’s a maximum income to qualify for legal aid. We could collect income data like this:

prompt = "Enter client's income, empty line to finish: "
client_income = input(prompt)
incomes = []

while client_income:
    #process client's income
    incomes.append(client_income)
    print(client_income, "saved")
    client_income = input(prompt)

The first input() statement is called a “priming read”, because it prepares the loop variable.