Important: this article is not released under a Creative Commons license and may not be copied or redistributed in any form. Please use our contact page to get in touch with us if you wish to reproduce the article.

Understanding Looping


Nitin Venkatesh's Gravatar

Nitin Venkatesh
published Jan. 5, 2014, 12:09 a.m.


What is a loop?

A loop is a control structure that allows for a piece of code to be repeated continually. In other words, the piece of code present inside a loop is executed until a preset condition is not met.

For example, let's write an algorithm for a cookie monster:

until no cookie in jar:
    eat cookie;

The first line until no cookie in jar: specifies the condition of the loop to be executed and the line eat cookie; specifies the action to be taken if condition is satisfied.

Let's unblur the cookie monster algorithm from a programming perspective,

while cookies != 0:
    eat(cookies)

The != in the condition statement of the program is called the operator and means not equal to. The eat(cookies) line passes the value of the cookies to the function eat() which performs the eating action. Let's not concern ourselves with functions for now, but instead focus on understanding the overall looping structure.

When we want to convert this algorithm into a program, we need to keep count of the cookies in the jar to know when the cookie monster needs to stop eating. Let's use the variable cookies to keep count of the cookies and decrease it's value by one once the cookie's been eaten.

while cookies != 0:
    eat(cookies)
    cookies = cookies - 1

And voila! We now have a cookie monster program working! The fully functioning python program for the cookie monster is available as a Gist for you to run locally.

What is a nested loop?

You might have guessed it by the name by now - it's a loop within a loop.

Let's use the clock as an example, we're going to be talking about hours, minutes and seconds.

1 day = 24 hours
1 hour = 60 minutes
1 minute = 60 seconds

When someone asks you how many seconds are there in an hour you quickly answer 3600 seconds. How did you do that? 60*60. Why? Because there are 60 minutes in an hour and each of those sixty minutes has 60 seconds.

So what we do is, we iterate over the number of seconds in each minute 60 times to get the number of seconds in an hour.

Here's an example to count the number of minutes in a day:

hours = int(input("Please enter number of hours: "))
i = 1
total = 0

#Looping through total number of hours
while i<= hours:

    # Setting iterator for minutes  
    j = 1
    # Looping through each minute for current hour
    while j <= 60:

        #Setting iterator for seconds
        k = 1
        # Looping through each second for current minute
        while k <=60:
            # Adding 1 to the value of total number of seconds counted
            total = total + 1
            k += 1
        j += 1
    i += 1

print("Total number of seconds in {} hours = {}".format(hours,total))

In the above program, we loop through each minute of the hour, which in turn loops through each second of that minute. Counting the seconds each time it is looped gives us the total number of seconds in an hour. This code is also available as a Gist for your comfort.

Examples of loops in everyday-life:

When we use summation either in billing, counting, or mathematics.

Summation example image

The above mathematical expression is represented by a loop that adds the value of 2n for values of n ranging from 1 to 100.

The equivalent code would be: (Gist)

total = 0
for n in range(1,100):
    total = total + (2*n)
print total

Double summation example image

The above mathematical expression is represented by a loop nested into another. For each value of y, all the values of x are looped through and the product of x and y is obtained. Basically, just the sum of all possible product combinations of x and y

The equivalent code would be: (Gist)

x = int(input("Enter x upper limit:"))
y = int(input("Enter y upper limit:"))
total = 0
i,j = 1,1
while i <= y:
    while j <= x:
        total = total + (x*y)
        j += 1
    i += 1
print total

Table data image

The above tabular data can be read using nested loops as well. Traversing through columns would be done by the inner loop and traversing through rows would be done by the outer loop. Here's a rough algorithm for it:

for row_val in row:
    for col_val in column:
        read(col_val)

Further reading:

Cross posted from Nitin's blog