A loop is a tool that allows use to tell Python to repeat a task several times, usualy with slight variations each time. We will consider two types of loops in this course: for loops and while loops.
We will begin with for loops, but before we can do so, we need to introduce the concept of a range.
The range(a, b)
function generates a list of integers beginning with a
and continuing up to, but NOT INCLUDING b
.
A range is not a list, but can be converted into a list.
my_range = range(3,8)
print(type(my_range))
print(my_range)
print(list(my_range))
We can use for loops to ask Python to repeat a task a certain number of times. The following example illustrates the basic syntax used to create a for loop.
for i in range(0,5):
print("This should print 5 times.")
At a basic level, the first line in the cell below told Python that it should execute the indented line 5 times. In truth, there is more going on under the hood of this for loop.
What is actually happening is that the variable i
starts out being equal to the first value in the range provided. Each time the loop executes, i
increments by 1 and the loop executes again. This process continues, with i
taking on each value within the range.
Thus, in this example, the print()
command executes 5 times: First with i=0
, then with i=1
, i=2
,i=3
, and finally with i=4
.
As it turns out, we can access the current value of i
from the body of the loop itself.
for i in range(0,5):
print(i)
for i in range(0,5):
print(i**2)
The example below illustrates two new ideas relating to for loops:
for i in range(1,11):
message = "The square of " + str(i) + " is " + str(i**2) + "."
print(message)
We can also use loops to alter variables that are defined outside of the loop.
# Sum the first 100 positive integers
total = 0
for i in range(1,101):
total += i
print(total)
The example above provides a usefull illustration of one of the ways that we can use a loop. However, we could have accomplished that particular task by using the sum()
function rather than a loop.
print(sum(range(1,101)))
Write a loop to find the sum of the squares of the first 50 positive integers. Store the sum in a variable called sum_of_squares
. Print this variable. You should get 42925.
# Find the sum of the squares of the first 50 positive integers.
sum_of_squares = 0
for i in range(1, 51):
sum_of_squares = sum_of_squares + i**2
print(sum_of_squares)
One common use of a loop is to perform an action on every element of a list. In this case, we treat the variable i
as an index for elements in the list.
The code in the next cell generates a random list that we will use in the following examples. You do not need to be concerned with understanding how this code works at the moment.
# Generate a random list of integers
import random
random.seed(1)
rand_list = random.sample(range(100), 30)
print(rand_list)
We have randomly generated a list of integers called rand_list
. We will now print out the square of every element in this list.
# print the square of each element in the rand_list
n = len(rand_list)
for i in range(0,n):
print("The square of " + str(rand_list[i]) + " is " + str(rand_list[i] ** 2))
# Create a list of squares of elts in rand_list
rand_squares = [] # Create a blank list.
for i in range(0, len(rand_list)):
rand_squares.append(rand_list[i] ** 2)
print(rand_squares)
# Double all of the elements of rand_list
for i in range(0, len(rand_list)):
rand_list[i] = rand_list[i] * 2
print(rand_list)
� Exercise
The code in the next cell creates two randomly generated lists, listA
and listB
. The lists are of the same (unknown) length. In the blank cell, write code to create a third list, listC
, so that for each index i
, listC[i]
is equal to 2 times listA[i]
plus 3 times listB[i]
.
Print the smallest and largest elements of listC
. If this was done correctly, these should be 58 and 2343.
random.seed(37)
size = random.choice(range(200,400))
listA = random.sample(range(500), size)
listB = random.sample(range(500), size)
listC = []
for i in range(0, len(listA)):
listC.append(2 * listA[i] + 3*listB[i])
print(min(listC))
print(max(listC))
In the loops that we have considered so far, we have created a temporary variable (typically called i
) that runs through all of the values in a given range. We can also loop over lists by creating a temporary variable that runs through all of the values in a given list.
SW = ['the phantom menace', 'attack of the clones', 'revenge of the sith', 'a new hope', 'the empire strikes back',
'return of the jedi', 'the force awakens']
print(SW)
for movie in SW:
print(movie)
for movie in SW:
print(movie.title())
It should be noted that this method of looping does not provide any new functionality. In fact, losing access to the index actually limits the applications that we can use a loop for. However, looping over a list directly can be a convenient shortcut for reading the elements of a list when we don't need to make any changes to the list and don't need care about the indices of the elements in the list.
For some complex tasks, it is necessary to include loops inside of other loops. This is called a nested loop. The simplest case of a nested loops is when we have one loop that itself contains another loop. In this case, we call the first loop that Python encounters the outer loop, and the loop inside of that is called the inner loop. Each time the outer loop runs, the entire inner loop will process, running through all of it's possible iterations.
To get an introduction to how nested loops work, consider the following example.
for i in range(0, 6):
for j in range(0, 3):
print("i is equal to " + str(i) + "; j is equal to " + str(j))
print("\n")
� Excercise
The following cell contains a list of lists, named A
. This list is intended to represent a 3x5 matrix. Each of the three lists inside A
represents a single row with 5 elements.
A = [ [11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25] ]
Write a loop that prints the rows of A
one at a time. This output will more closely resemble a matrix.
for row in A:
print(row)
Create an empty list called ASquare
. Use nested loops to turn ASquare
into a matrix such that each element of ASquare
is equal to the square of the corresponding element in A
.
ASquare = []
for i in range(0,3):
tempRow = []
for j in range(0,5):
tempRow.append(A[i][j] ** 2)
ASquare.append(tempRow)
Print the list ASquare
, one row at a time.
for row in ASquare:
print(row)