Updated date:

Looping Constructs in Python

I'm a software developer with a great interest in data analysis and statistics.

looping-constructs-in-python

Looping constructs in any programming language are used to perform a sequence of steps repeatedly for a given number of times. Python allows two types of loops – the for loop and the while loop. It is also possible to add a loop in another loop and create a nested loop in Python.

The For Loop

While iterating over a tuple or list, we can either use indices and write a traditional for loop that is similar to the one found in C/C++ or write a for-each-sequence loop similar to that in Java. Let us learn more about for loops.

Iterating Over Building Blocks of a Sequence

#!/usr/bin/python3
print("Printing letters of string in each line... ")
for cur in 'Hello World!':     
    print (cur)

rhymes = ['Mary','Had','A','Little','Lamb']
print("Printing words in the rhyme in each line...")
for word in rhymes:        
    print (word)

print ("...Reached the end...")

In the first for loop, we take the string ‘HelloWorld!’ sequence and iterate over it using iteration variable. In general, the syntax of this type of for loop can be expressed as:

for iter_var in sequence:
       # steps inside for loop.

The first two for loops show how letters in a string and words in a list representing a phrase are treated as individual building blocks of the sequence.

The output for the above program will be:

Printing letters of string in each line...
H
e
l
l
o
W
o
r
l
d
!
Printing words in the rhyme in each line...
Mary
Had
A
Little
Lamb
 ...Reached the end...

This type of for loop can be applied in case of a tuple or a dictionary as well. The code below demonstrates how to iterate over a dictionary considering the keys or key-value pairs as the building blocks of the sequence.

#!/usr/bin/python3

print("Iterating over a dictionary")
studentDict = {'firstName': 'john','lastName':'Smith', 'age': 29, 'studentId':415312}

print("Iterating using a key alone in for loop")
for key in studentDict:
    print("key: ", key, ", value: ", studentDict[key])

print("Iterating using key and value")
for foo,bar in studentDict.items():
    print("key: ", foo, ", value: ", bar)
print ("...Reached the end...")

In the first for loop, we iterate over the dictionary using key alone. In second for loop, both key and value are used as iteration variables to iterate over the items in the dictionary named "studentDict". Note that it is not mandatory to mention the name as ‘key’ and ‘value’ always in the for loop and to demonstrate it, we have used foo and bar.

Output for the above code will be:

Iterating over a dictionary
Iterating using a key alone in for loop
key:  firstName , value:  john
key:  studentId , value:  415312
key:  lastName , value:  Smith
key:  age , value:  29
Iterating using key and value
key:  firstName , value:  john
key:  studentId , value:  415312
key:  lastName , value:  Smith
key:  age , value:  29
...Reached the end...

Iterating Over Sequence Using Index and Range

This is similar to the for loops that we see in languages like C/C++/Java etc. Elements of a given sequence are accessed using index.

The range() function is used to return a range of values starting from zero as lower bound to the value mentioned as a parameter in the upper bound. It is possible to get a sub-range by mentioning a lower bound and upper bound.

For example, range(2,6) returns 2, 3, 4, 5 whereas range(3) will return 0, 1, 2. In the following code, we use range(len(rhymes)) to direct python to iterate over positions 0, 1, 2, till the rhymes[length – 1] and print the values.

#!/usr/bin/python3
rhymes = ['Mary','Had','A','Little','Lamb']

print("Printing each word in new line accessed by index.")
for index in range(len(rhymes)):
    print (rhymes[index])

The output for the above code will be:

Printing each word in new line accessed by index.
Mary
Had
A
Little
Lamb

The While Loop

The general syntax of while loop can be represented as follows:

while condition:
    # do these steps

It repeatedly executes the steps as long as the condition holds true. So, an infinite loop can be easily written using this while loop just like how we create it in C/C++/Java using:

test = 1
while test == 1:
    # do these steps infinite number of times

In the following program, we print numbers from 11 to 20 using a simple while loop.

#!/usr/bin/python3

print("Counting from 11 to 20")
count = 11
while count<=20:
    print(count)
    count = count + 1

The output of the above program will be as follows:

Counting from 11 to 20
11
12
13
14
15
16
17
18
19
20

Nested Loops

It is possible to nest a loop within another loop. Consider the following sample program. It is designed to print a number pyramid in the following manner:

1
1 2
1 2 3
1 2 3 … n 

#!/usr/bin/python3

# Program to print a number pyramid like:
for i in range(1,6):
    for j in range(1, i+1):
        print (j, end=" ")
    print("")

In the first for loop, we specify the range’s lower limit as 1 and upper limit as 5+1. In the second loop, we specify the range from 1 to i+1 for each line. Note that the print statement has a parameter named end=” “.

This is to direct the interpreter to print further outputs in the same line and all these outputs shall be separated using the special character shown. If the statement is changed to print (j, end=", "), all numbers will have a trailing comma. Output for the above program will be:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Loop Control Statements

Python offers three control statements:

  • Break statement – It terminates the loop statement and transfers the control outside the scope to the next statement following the loop.
  • Continue statement – It causes the loop to skip the remaining steps of the loop but continue with the next iteration.
  • Pass statement – It is often useful for debugging the code. Nothing really happens when the statement is executed.

Let us learn more about these statements with an example:

#!/usr/bin/python3
print('Printing letters in Welcome till letter l')
for letter in 'Welcome':
    if letter == 'l':
        break
    print (letter, end=", ")
    
print("")
print('Printing letters in welcome after omitting l')
for letter in 'Welcome':
    if letter == 'l':
        continue
    print (letter, end=", ")
print(" ")
print("Adding pass block when l is encountered")
for letter in 'Welcome':
    if letter == 'l':
        pass
        print(" ")
        print("Encountered pass block")
        print("Continue printing")
    print (letter, end=", ")

The output of the above code will be as follows:

Printing letters in Welcome till letter l
W, e,
Printing letters in welcome after omitting l
W, e, c, o, m, e, 
Adding pass block when l is encountered
W, e, 
Encountered pass block
Continue printing
l, c, o, m, e,

© 2019 Sam Shepards

Related Articles