Skip to content

For Loops

For Loops

For loops are a component of many programming languages. A for loop is a programming structure where a section of code is run a specified number of times.

Say we want to print out the statements:

Engineers solve problems in teams
Engineers solve problems in teams
Engineers solve problems in teams

We want to see the statement printed three times. One way to do accomplish this is with three print statments in a row:

In [1]:
print('Engineers solve problems in teams')
print('Engineers solve problems in teams')
print('Engineers solve problems in teams')

Engineers solve problems in teams
Engineers solve problems in teams
Engineers solve problems in teams

But coding the same print statement three times is inefficient and repetitive. Another way to accomplish the same task is to use a for loop.

For Loops with range()

Another method to print the same statement three times is to use a for loop. A for loop is a programming structure where a user-defined block of code runs a specified number of times. The basic structure of a for loop in Python is below:

for var in range(num):
    code

Where var can be any variable name, range(num) is the number of times the for loop will run, and code are the lines of code that execute each time the loop runs. Note the for loop starts with the keyword for and includes a colon :. Both for and the colon : are required. Also note that code was indented. Each statement that runs as part of the for loop needs to be indented the same number of spaces. The standard indentation is 4 spaces. Jupyter notebooks and most code editors automatically indent lines of code after a for loop is initiated.

Let's rewrite the previous example using a for loop:

In [2]:
for i in range(3):
    print('Engineers solve problems in teams')

Engineers solve problems in teams
Engineers solve problems in teams
Engineers solve problems in teams

Python's range() function returns an an iterable list of values starting from zero and ending at n-1. For instance, when range(3) is called, the values 0, 1, 2 are returned. Note the number 3 is not part of the values range(3) returns, even though the function input was (3). Python's counting starts at can be confirmed with a for loop:
In [3]:
for i in range(3):
    print(f'This is range number: {i}')

This is range number: 0
This is range number: 1
This is range number: 2

For loops with lists

For loops can also be run using Python lists. If a list is used, the loop will run as many times as there are items in the list. The general structure is:

for <var> in <list>:
    <statements>

Where <var> is a variable name assigned to the item in the list, <list> is the list object and <statements> are the programming statements that run for each item in the list.

An example of a for loop using a list is below:

In [4]:
my_list = ['electical','mechanical','civil']
for item in my_list:
    print(item)
electical
mechanical
civil

The for loop ran three times, because there are three items in the list. Each time through the loop the variable item was set to one particular item in the list. The first time through the loop, item='electrical'. The second time through the loop item='mechanical' and the third time through the loop item='civil'.

For loops in iterative calculations

For loops can be used to make iterative calculations. An iterative calculation is a calculation repeats over and over, using the returns from a previous calculation in the next calculation. An example of an iterative calculation is calculating factorials.

n! = 1\times2 \ \times...\times \ n

To calculate five factorial, 5!, we can repeat the same calculation over and over, using the result of the previous calculation in the next calculation:

1
1\times2=2
2\times3=6
6\times4=24
24\times5=120

This iterative calculation can be coded with a for loop. In the body of the loop, set n=n*(i+1) where n on the right-hand side of the assignment operator(=) is the result of the previous calculation. n on the left-hand side of the assignment operator is the new value of n that will be used in the next calculation- the next time through the for loop.

Note we are using i+1 instead of i as the increment in our calculation because Python numbering starts at 0 and ends at n-1. The line print(f'5 factorial = {n}') does not run until the for loop completes because the print line is not indented. The line n = n * (i+1) runs 5 times because it is indented.

In [5]:
n = 1

for i in range(5): n = n * (i+1)

print(f'5 factorial = {n}')

5 factorial = 120

Let's try another iterative calculation. The Fibonacci sequence is a sequence of numbers where the next number in the sequence is equal to the sum of the two previous numbers in the sequence. For example the Fibonacci sequence to seven terms long is:

1, \ 1, \ 2, \ 3, \ 5,\ 8,\ 13

The next number in the Fibonacci sequence, F_n, can be calculated in terms of the previous two numbers in the sequence F_{n-1} and F_{n-2}.

F_n = F_{n-1} + F_{n-2}

We can code the Fibonacci sequence eight terms long using a for loop. The first two terms of the Fibonacci sequence F_1 and F_2 need to be defined before the loops starts.

Then each time through the loop: * the next term in the sequence F equals F_1 (the last number) and F_2 (the second to last number). * F_2 becomes the second to last number (the value of the number F_1) * F_1 becomes the last number (the value of F).

In [6]:
F_1 = 1
F_2 = 1

for i in range(7): print(F_2, end=' ') F = F_1 + F_2 F_2 = F_1 F_1 = F

1 1 2 3 5 8 13