7  Loops

In programming often times there is a requirement that a particular set of instructions is required to be repeated certain number of times. This can be easily achieved using loops. These statements execute a code block repeatedly for specified number of times or until a condition is met.

7.1 For loop

The most common loop that is used to repeat a block of code for fixed number of times is for loop. The example below show iterating through all the elements of a list. Syntactically, the for code block is similar to the if block in terms of the use of colon and indentation.

list_of_numbers = [1, 2, 3, 4, 5] 
for x in list_of_numbers:
    print(x*2)
print("Done")
2
4
6
8
10
Done

The for statement begins with the for keyword which is followed by a variable name (x in the example above). This variable would store the different elements in the list as the loop progressess. The in keyword connects the variable with the list and finally we have the list that we want to iterate. The colon (:) at the end is required. It indicates the begining of the block of statements that would be part of the for loop. Next, we have a set of statement that needs to executed for each element of the list. The statement that are part of the for loop must begin with indentation (tab or some spaces). In the example above, the print(x*2) statement is part of the for loop (since it is indented) while the print("Done") statement is not part of the for loop since it is not indented. There must be atleast one statement which is part of the for loop (i.e. atleast one statement that starts with indentation).

7.2 Keeping track of indices during iteration

In the code above, we were able to iterate through the items in a list using a for loop and perform some action on each of those items. However, there was no option to keep track of the index of an item during iteration. For cases where we need a list item along with its index, we can use the enumerate function with a list as an argument. This function returns an enumerate object having a collection tuples – each of which has the index and the corresponding item in the list. When using this in a for loop, we need to provide two variables to store the two values from the tuple.

nums = [10,20,30,40,50]
for x,y in enumerate(nums):
    print(x,y)
0 10
1 20
2 30
3 40
4 50

The default indexing for the enumerate function start with zero; which can be changed using the start keyword argument.

nums = range(10,51,10)
for x,y in enumerate(nums, start=1):
    print(x,y)
1 10
2 20
3 30
4 40
5 50

7.3 Iterating through multiple lists simultaneously

The zip function comes handy when the objective is to iterate through multiple lists (or other iterable python objects) at the same time. It returns a collection of tuples such that the nth tuple in this collection has nth element from all the lists passed as an argument. If the lists (which are passed as an argument to zip) are of unequal length then the iteration continues till the length of the shortest list. When running a for loop with zip, the number of variable should be equal to the number of lists passed to zip such that each items gets assigned to a different variable. A single variable can also be used in the for loop, in that case, that variable would be a tuple having the corresponding items.

fruits = ["Apple", "Banana", "Banana"]
desserts = ["pie", "pie", "shake"]
for x,y in zip(fruits, desserts):
    print(x,y)
Apple pie
Banana pie
Banana shake
for x in zip(range(10,51,10),"abcde"):
    print(x[0],x[1])
10 a
20 b
30 c
40 d
50 e

Quiz: Write a program that takes a list of 10 numbers as input and prints the cube of each of the number in the list.

Show answer
x = range(1,11)
for y in x:
    print(y**3)

We can also check multiple conditions at the same time. For this the Boolean operators (and, or, and not) are used along with the different conditions.

7.4 While loop

While loop is another frequently used construct to perform task repeatedly when the number of iterations is not fixed. This loop is executed till certain condition is met irrespective of number of iterations.

While expression:

    code block

While loop implicitly has a if conditional statement.

x = 5
while(x>2):
    print(x)
    x = x-1
print("Loop is over")
5
4
3
Loop is over

When writting a while loop you must ensure that the condition is met at some point within the loop otherwise the loop will iterate infinitely. E.g. in the above code if the condition within while loop is changed to x>2 then it result in an infinite loop.

7.5 Controlling the execution of loops

Many a times it is require to skip the execution of loop for certain steps or to terminate the loop altogether. Python has some reserved keyword to facilitate this task. continue can be used to jump to subsequent iteration of the loop and break can be used to end the loop. These special keywords are generally used in conjuction with conditional statements to manipulate the execution of the loops.

for x in range (1,10):
    if (x == 5):
        continue
    print(x)
print("Done")
1
2
3
4
6
7
8
9
Done
for x in range (1,10):
    if (x == 5):
        break
    print(x)
print("Done")
1
2
3
4
Done

Quiz: Take a list of first 10 numbers and print the square for even numbers.

Show answer
for x in range(1,11):
    if(x%2 == 0):
        print(x**2)
    else:
        continue