Everything that we have seen so far has involved us giving a program a single instruction and asking it to run. This is not particularly efficient if we want to do the same thing several times over. We would much rather find a way to automate this and run the task multiple times for us, for loops are the perfect way to get started here.

Lists

We cover lists and other group concepts elsewhere, but a list is simply a way to group lots of things into one variable. A list has lots of functions that make it easy to work with – please see its own page for more on this. This list is a 3-a-side team selected to play in a TV commercial.

In [1]:
TeamA = ["Nasta","Overvenus","Ranalda"]

The TV commercial wants to announce these players to the crowd. We can do this individually for each:

In [2]:
print("Welcome to the cage, " + TeamA[0])
print("Welcome to the cage, " + TeamA[1])
print("Welcome to the cage, " + TeamA[2])
Welcome to the cage, Nasta
Welcome to the cage, Overvenus
Welcome to the cage, Ranalda

Notice how we repeated ourself three times? ‘For loops’ help us to avoid doing so. The smarter announcer is run using the following code:

In [3]:
for player in TeamA:
    print("Welcome to the cage, " + player)
Welcome to the cage, Nasta
Welcome to the cage, Overvenus
Welcome to the cage, Ranalda

Our output is exactly the same, but the code looks so much better!

The essential bits to our code are the words ‘for’ and ‘in’, ***

Plus, we could also add a second team really really easily with a ‘nested for-loop’ – this is a for-loop inside a for-loop!

In [4]:
#Team 2, enter!
TeamB = ["Tatti","Nikita","Hanry"]

#A list of lists!
Teams = [TeamA,TeamB]

for team in Teams:
    for player in team:
        print("Welcome to the cage, " + player)
Welcome to the cage, Nasta
Welcome to the cage, Overvenus
Welcome to the cage, Ranalda
Welcome to the cage, Tatti
Welcome to the cage, Nikita
Welcome to the cage, Hanry

So cool!

Summary

If we have to write down every single thing that we want our code to do, it will be hugely inefficient and a bit of a pain to write. We can utilise for loops to automate any repetition and to try our best to avoid duplicate code. In fact, programming has a DRY mantra – “Don’t repeat yourself”.

Our examples above demonstrate a nested for-loop too – a loop within a loop to push our automation even further.

Give them a try yourself, and check out while loops when you’re comfortable here!