Loops (Need)

Figure 1: From xkcd.

What to expect in this chapter

One of the most powerful features of programming is the ability to repeat a task over and over again. This can be as mundane as renaming a set of files or more involved, like running the same statistical analysis on many experimental data sets. While humans quickly become tired (and bored) with such tasks, computers excel at mindless repetitive tasks. This section will show you how to repeat things in Python. This topic is called loops or iterations and is one of the most valuable features of any programming language.

Python offers two mechanisms for looping. One is the for statement, and the other is the while statement. We will spend more time on the former as it is the more used of the two.

1 The for iterator

Let me quickly show you a few examples of using a for loop.

Let’s say I want to print a message corresponding to every superhero in the following list.

real_names = ["Natasha Romanoff", "Tony Stark", "Stephen Strange"]

Here is one (poor) way of doing this.

name=real_names[0]
print(f"{name} is a Marvel superhero!")

name=real_names[1]
print(f"{name} is a Marvel superhero!")

name=real_names[2]
print(f"{name} is a Marvel superhero!")
Natasha Romanoff is a Marvel superhero!
Tony Stark is a Marvel superhero!
Stephen Strange is a Marvel superhero!

This way of programming is not very good because:

  1. it does not scale very well (imagine if you have a 100 names!),
  2. it is cumbersome to make changes, you have to do it three times.
  3. it is highly error prone, since you need to type something new (even if you are copying and pasting most of it).

This is where a for loop can come in handy.

1.1 for with a list

I can achieve the same result using a for loop as follows:

for name in real_names:
    print(f"{name} is a Marvel superhero!")
Natasha Romanoff is a Marvel superhero!
Tony Stark is a Marvel superhero!
Stephen Strange is a Marvel superhero!

Notice the structure of the for loop;

  • it goes through the list and assigns name the value of each element of the list.
  • it then runs the code-block using this value of name.
  • the code block is deginted by using : and tabs like with if.
Remember

Remember that for can be used to directly loop through a list.

By the way, there is nothing special about the names of the variables I have used. The following will work too. However, it will not be very readable because x is a bit cryptic in this context.

for x in real_names:
    print(f"{x} is a Marvel superhero!")

1.2 for with enumerate

Let’s say we want to do a bit more, like using the information in both of the following lists.

super_names = ["Black Widow", "Iron Man", "Doctor Strange"]
real_names = ["Natasha Romanoff", "Tony Stark", "Stephen Strange"]

Since the for loop only accepts one list, we need to do something else to access the data in both lists. One option is to use enumerate(). Let me first show you how enumerate() works.

for count, name in enumerate(real_names):
    print(f'{count}: {name} is a Marvel superhero!')
0: Natasha Romanoff is a Marvel superhero!
1: Tony Stark is a Marvel superhero!
2: Stephen Strange is a Marvel superhero!

You can think of enumerate() as something that keeps count. In the above example, enumerate() not only gives the elements of the list, it also gives you a number (that is stored in count).

Other than counting, we can use the count given by enumerate() to index the other list!

for index, name in enumerate(real_names):
    superhero_name = super_names[index]
    print(f'{name} is {superhero_name}!')
Natasha Romanoff is Black Widow!
Tony Stark is Iron Man!
Stephen Strange is Doctor Strange!

Before we move on, I would like to highlight two things:

  1. Notice how I changed the variable name used with enumerate() to (count and index) to match their logical use. This makes it easy to iimediately see what you are doing (i.e., the intention) wiht the code. Python does not really care abot this, but remember that we write programmes for humans!

  2. Although by default, enumerate() starts counting from 0, we can easily change it to start at another value, say 100.

    for count, name in enumerate(real_names, 100):
        print(f'{count}: {name} is a Marvel superhero!')
    100: Natasha Romanoff is a Marvel superhero!
    101: Tony Stark is a Marvel superhero!
    102: Stephen Strange is a Marvel superhero!
Remember

Remember that for can be combined with enumerate() to count while looping through a list.

1.3 for with range

Yet, another way to achieve the result above is by using the function range(). But, first lets see what range() can do.

  1. for i in range(5):
        print(i)

    We can use range() to get the for loop to run a given number of loops (5 in this example).

    0
    1
    2
    3
    4
  2. for i in range(5, 10):
        print(i)

    We can tailor the starting and ending values…

    5
    6
    7
    8
    9
  3. for i in range(1, 10, 3):
        print(i)

    We can even adjust the step size.

    1
    4
    7

Note:

  • Functions like range() and enumerate() only work with looping structures.
  • range() always ends one short of the ending number.

Now, let’s return to our initial problem of printing superhero names. We can use range() as follows:

for i in range(len(real_names)):
    real_name = real_names[i]
    super_name = super_names[i]        
    print(f"{real_name} is Marvel's {super_name}!")
Natasha Romanoff is Marvel's Black Widow!
Tony Stark is Marvel's Iron Man!
Stephen Strange is Marvel's Doctor Strange!

Notice that I have used the len(real_names) to get how many times the loop should run.

Remember

Remember that for can be run a given number of times using range().

2 while

number = 0

while number < 5:
    print(number)
    number += 1

Now let’s take a quick look at the while loop. A while loop is set up so that it keeps on running while a condition is True. So the while loop checks the condition at the start and begins another loop if it is True.

In the adjoining example the loop keeps on going while the number is less than 5.

A useful feature of the while loop is that you do not need to know beforehand how many iterations are needed.

0
1
2
3
4
Back to top