Python Looping


4: Looping


4.1 INTRODUCTION

When we were young, we were taught tables of numbers. The table of a number had a pattern. Writing a table in an examination required writing, say, n×” followed by i  (i varying from 1 to n) and then the result of calculations (that is n × 1, n × 2 and so on). Many such situations require us to repeat a given task many times. This repetition can be used to calculate the value of a function, to print a pattern or to simply repeat something. This chapter discusses loops and iterations, which are an integral part of procedural programming. Looping means repeating a set of statements until a condition is true. The number of times this set is repeated depends on the test condition. Also, what is to be repeated needs to be chalked out with due deliberation. In general, repeating a block requires the following (Figure 4.1).

Figure 4.1: Looping



Python provides two types of loops: for and while  (Figure 4.2).

Figure 4.2: Loops in Python



While loop is one of the most general constructs in any programming language. If you come from a “C” background, you must be equipped with the above construct. While  loop retains most of its features in Python as well, however, there are notable differences too.

The while loop repeats a block, identified by indentation, until the test condition remains true. As we will see in the following discussion, one can come out of the loop using break and continue. Also, to decide if the loop repeats as per the test condition after which the else  condition executes. This is an additional feature in Python.

The use of for in Python is a bit different to “C”-like languages. The for construct in Python is generally used for lists, tuples, strings, etc. The chapter presents range, which will help the programmer to select a value from a given range. The reader is advised to go through the discussion of lists and tuples presented in Chapter 2 of this book before starting with the for  loop.

The chapter has been organized as follows. Section 4.2 of this chapter presents the basics of the while loop. Section 4.3 uses looping to create patterns. Section 4.4 introduces the concept of nesting and presents the processing of lists and tuples using for  loops. The last section concludes the chapter.

 

4.2 WHILE

In Python, the while loop is the most commonly used construct for repeating a task over and over again. The task is repeated until the test condition remains true, after which the loop ends and if the exit occurs without a break, then the else  part of the construct executes. The syntax of the loop is as follows:

Syntax

 

while test:

      ...

      ...

else:

     ...

It may be stated here that the body of the loop is determined by indentation. This is the reason why you must be extremely careful with indentation. Also, the else  part is an addition in Python when compared to “C”-like languages. In order to understand the concept, let us go through the following illustrations.

Illustration 4.1

Ask the user to enter a number and calculate its factorial.

Solution:  The factorial of a number n is defined as follows.

factorial = 1 × 2 × 3 × … × n

That is the factorial of a number, n, is the product of n terms starting from 1. To calculate the factorial of a given number, first of all the user is asked to input a number. The number is then converted into an integer. This is followed by the initialization of factorial by 1. Then a while loop successively multiplies i to 'factorial' (note that after each iteration the value of i  increases by 1). The following program calculates the factorial of a number entered by the user.

Program

 

n = input('Enter number whose factorial is required')#ask user to enter number

m = int(n)#convert the input to an integer

factorial = 1#initialize

i=1# counter

while i<=m:

    factorial =factorial*i

    i=i+1

print('\factorial of '+str(m)+' is '+str(factorial))

Output

 

>>>  

RUN C:/Users/ACER ASPIRE/AppData/Local/Programs/Python/Python35-32/Tools/scripts/factorial.py

Enter number whose factorial is required6

Factorial of 6 is 720

 

Illustration 4.2

Ask the user to enter two numbers a and b and calculate a to the power of b.”

Solution:  a raised to the power of b can be defined as follows.

power = a × a × a × .. × a (b times)

That is, the power of a number a raised to b is the product of the number a,” b times. To calculate the power, first of all the user is asked to input two numbers. The numbers are then converted into integers. This is followed by the initialization of 'power' by 1. Then a while loop successively multiplies 'a' to 'power' (note that after each iteration the value of i  increases by 1). The following program implements the above logic.

Program

 

>>>  

a = int(input('Enter the first number'))

b = int(input('Enter the second number'))

power=1

i = 1

while i < = b:

    power = power*a

    i=i+1

else:

    print(str(a)+' to the power of '+str(b)+' is '+str(power))

Output

 

>>>  

RUN C:/Users/ACER ASPIRE/AppData/Local/Programs/Python/Python35-32/Tools/scripts/power.py

Enter the first number4

Enter the second number5

4 to the power of 5 is 1024

>>> 

 

Illustration 4.3

The arithmetic progression is obtained by adding the common difference d to the first term a,” successively. The ith term of the arithmetic progression is given by the following formula:

T (i) = a + (i – 1) × d

Ask the user to enter the value of a,” d, and n (the number of terms), and find all the terms of the AP. Also, find the sum of all the terms.

Solution: The following program asks the user to enter the values of a,” “d,” and n.” Note that the input is converted into integers. Also, since all the terms are to be calculated, this evaluation is done inside a loop. The 'sum' is initialized to 0 and the terms are added to 'sum'  in each iteration.

Program

 

>>>  

a = int(input('Enter the first term of the Arithmetic Progression\t:'))

d = int(input('Enter the common

difference\t:')) n = int(input('Enter the number of terms\t:')) i = 1

sum = 0#initialize

while i<=n:

    term = a +(i-1)*d

    print('The '+str(i)+'th term is '+str(term))

    sum = sum + term

    i=i+1

else:

    print('The sum of '+str(n)+' terms is\t:'+str(sum))

Output

 

RUN C:/Users/ACER ASPIRE/AppData/Local/Programs/Python/Python35-32/Tools/scripts/AP.py

Enter the first term of the Arithmetic Progression :5

Enter the common difference :6

Enter the number of terms :7

The 1th term is 5

The 2th term is 11

The 3th term is 17

The 4th term is 23

The 5th term is 29

The 6th term is 35

The 7th term is 41

The sum of 7 terms is :161

 

Illustration 4.4

The geometric progression is obtained by multiplying the common ratio 'r' to the first term 'a' , successively. The ith term of the progression is given by the following formula. T(i) = a × ri – 1

Ask the user to enter the value of 'a''r', and 'n' (the number of terms), and find all the terms of the GP. Also, find the sum of all the terms.

Solution: The following program asks the user to enter the values of 'a''r', and 'n'. Since all the terms are to be calculated, this evaluation is done inside a loop. The 'sum' is initialized to 0 and the terms are added to 'sum'  in each iteration.

Program

 

>>>  

a = int(input('Enter the first term of the Geometric Progression\t:'))

r = int(input('Enter the common ratio\t:'))

n = int(input('Enter the number of terms\t:'))

i = 1

sum = 0#initialize

while i<=n:

    term = a * (r**(i-1))

    print('The '+str(i)+'th term is '+str(term))

    sum = sum + term

    i=i+1

else:

    print('The sum of '+str(n)+' terms is\t:'+str(sum))

Output

 

>>>  

RUN C:/Users/ACER ASPIRE/AppData/Local/Programs/Python/Python 35-32/Tools/scripts/GP.py

Enter the first term of the Arithmetic Progression :5

Enter the common ratio 3

Enter the number of terms 5

The 1th term is 5

The 2th term is 15

The 3th term is 45

The 4th term is 135

The 5th term is 405

The sum of 5 terms is 605

 

4.3 PATTERNS

Have you ever wondered why quizzes and riddles form an integral part of any intelligence test? The following incident will help the reader to understand the importance of patterns. During World War II, the British were striving hard to break Enigma, the machine used by the Germans for encrypting their messages. The army somehow recruited Alan Turing, who was never in his lifetime recognized, for the above task. He wanted a team to help him, for which he conducted an exam. Many of you would be amazed to know what he asked in that exam which would determine the destiny of a country! He asked the candidates to solve the given puzzles in a given time. This incident underlines the importance of comprehending patterns. What happened thereafter is history. Decoding patterns and solving puzzles helps to judge the intellect of a person. This is much more important than learning a formula. This section presents the designing of patterns using loops to help the reader understand the concept of nesting. Moreover, this book also intends to inculcate the problem solving approach in the reader. Therefore this section becomes all the more important.

The following illustrations show how to assign values to the counters of the inner and the outer loops to carry out the given task. The patterns, as such, may not be very useful. However, doing the following program would help the reader to comprehend the concept of nesting. The methodology of making a pattern has been explained in each of the following programs.

Illustration 4.5

Write a program to generate the following pattern in Python.

 

*

* *

* * *

* * * *

The number of rows would be entered by the user.

Solution: The number of rows n, will determine the value of the counter (from 0 to n). The value of i denotes the row number in the following program. In each row, the number of stars is equal to the row number. The values of j, in each iteration, denotes the number of stars in each row. This loop is therefore nested. Also, note that after the inner loop ends a new line is printed using the print()  function.

Program

 

>>>  

n = input('Enter the number of rows')

m = int(n)

*k=1

for i in range(m):

   for j in range(1, i+2):

     print('*', end=" ")

   print()

Output

 

RUN C:/Users/ACER ASPIRE/AppData/Local/Programs/Python/Python35-32/Tools/scripts/loop2.py

Enter the number of rows 5

*

* *

* * *

* * * *

 

Illustration 4.6

Write a program to generate the following pattern in Python.

 

1

2 2

3 3 3

4 4 4 4

The number of rows would be entered by the user.

Solution: The number of rows will determine the value of the counter i, (from 0 to n). The value of i denotes the row number in the following program. In each row, the number of elements is equal to the row number. The values of j in each iteration denote the number of elements in each row. This loop is therefore nested. The element printed is the value of i+1. Also, note that after the inner loop ends a new line is printed using the print()  function.

Program

 

>>>  

n = input('Enter the number of rows')

m = int(n)

k=1

for i in range(m):

   for j in range(1, i+2):

     print(i+1, end=" ")

   print()

Output

 

RUN C:/Users/ACER ASPIRE/AppData/Local/Programs/Python/Python35-32/Tools/scripts/loop2.py

Enter the number of rows5

1

2 2

3 3 3

4 4 4 4

5 5 5 5 5

 

Illustration 4.7

Write a program to generate the following pattern in Python.

 

2

2 3

2 3 4

2 3 4 5

The number of rows would be entered by the user.

Solution: The number of rows, entered by the user, will determine the value of i (from 0 to n). The value of i denotes the row number in the following program. In each row, the number of elements is equal to the row number. The values of j in each iteration denote the number of elements in each row. This loop is therefore nested. The element printed is the value of j+1. Also note that after the inner loop ends a new line is printed using the print()  function.

Program

 

>>>  

n = input('Enter the number of rows')

m = int(n)

k=1

for i in range(m):

   for j in range(1, i+2):

     print(j+1, end=" ")

   print()

Output

 

>>>  

RUN C:/Users/ACER ASPIRE/AppData/Local/Programs/Python/Python35-32/Tools/scripts/loop3.py

Enter the number of rows5

2

2 3

2 3 4

2 3 4 5

2 3 4 5 6

 

Illustration 4.8

Write a program to generate the following pattern in Python.

 

1

2 3

4 5 6

7 8 9 10

The number of rows would be entered by the user.

Solution: The value of i denotes the row number in the following program. In each row, the number of elements is equal to the row number. The values of i in each iteration will denote the number of elements in each row. This loop is therefore nested. The element printed is the value of k, which starts from 1 and incrementally increases in each iteration. Also note that after the inner loop ends a new line is printed using the print()  function.

Program

 

>>>  

n = input('Enter the number of rows')

m = int(n)

k=1

for i in range(m):

   for j in range(1, i+2):

     print(k, end=" ")

     k=k+1

   print()

Output

 

>>>  

RUN C:\Users\ACER ASPIRE\AppData\Local\Programs\Python\ Python35-32\Tools\scripts\loop1.py

Enter the number of rows7

1

2 3

4 5 6

7 8 9 10

11 12 13 14 15

16 17 18 19 20 21

22 23 24 25 26 27 28

 

Illustration 4.9

Write a program to generate the following pattern in Python.

 

     *

    ***

   *****

  *******

 *********

The number of rows would be entered by the user.

Solution: The value of i denotes the row number in the following program. In each row, the number of stars is equal to the row number. The values of k in each iteration denote the number of stars in each row, which ranges from 0 to (2*i +1). This loop is therefore nested. The leading spaces are governed by the value of j, which ranges from 0 to (m-i-1). This is because if the value of i is 0, the number of spaces should be 4 (if the value of n is 5). In case the value of i is 1, the number of spaces should be 3 and so on. Also note that after the inner loop ends a new line is printed using the print()  function.

Program

 

n = input('Enter the number of rows')

m = int(n)

for i in range(m):

   for j in range(0, (m-i-1)):

     print(' ', end="")

   for k in range(0, 2*i+1):

     print('*',end="")

print()

>>>  

Output

 

RUN C:/Users/ACER ASPIRE/AppData/Local/Programs/Python/Python35-32/Tools/scripts/loop5.py

Enter the number of rows 6

*
***
*****
*******
*********

 

4.4 NESTING AND APPLICATIONS OF LOOPS IN LISTS

Nested loops can be used to generate matrices. In order to do this, the outer loop is designed to govern the rows and the inner loop to govern each element of a particular row. The following illustration shows the generation of a matrix having ith element given by the following formula:

ai, j  = 5 × (i + j)2

Note that in the following illustration, two loops have been used. The outer loop runs n times where n is the number of rows, and the inner loop runs m times where m  is the number of columns. The number of columns can be perceived as the number of elements in each row.

The inner loop has one statement, which calculates the element. At the end of each iteration (of the outer loop) a new line is printed using the print()  function.

Illustration 4.10

Generate a n × m , matrix, wherein each element (aij), is given by

ai, j  = 5 × (i + j)2

Solution:  The concept has been explained in the above discussion. There will be two loops; the outer loop for the number of rows and the inner loop for the number of columns.

Program

 

n = int(input('Enter the number of rows'))

m = int(input('Enter the number of columns'))

for i in range (n):

   for j in range(m):

     element = 5*(i+j)*(i+j)

     print(element, sep=' ', end= ' ')

   print() >>>

Output

 

RUN C:/Users/ACER ASPIRE/AppData/Local/Programs/Python/Python35-32/Tools/scripts/matrixgeneartion.py

Enter the number of rows3

Enter the number of columns3

0 5 20

5 20 45

20 45 80

>>> 

It may be noted that in the following chapters, this nesting is used to deal with most of the operations of matrices. As a matter of fact addition and subtraction of two matrices requires two levels of nesting, whereas multiplication of two matrices requires three levels of nesting.

 

Illustration 4.11: Handling list of lists

Note that in the following program the first list’s second element is itself a list. Its first element can be accessed by writing hb[0][1] and the first letter of the first element of the nested list would be hb[0][1][0] .

Program

 

>>>  

hb=["Programming in C#",["Oxford University Press", 2015]]

rm=["SE is everything",["Obscure Publishers", 2015]]

authors=[hb, rm]

print(authors)

print("List:\n"+str(authors[0])+"\n"+str(authors[1])+"\n")

print("Name of books\n"+str(authors[0][0])+"\n"+

                                  str(authors[1][0])+"\n")

print("Details of the books\n"+str(authors[0][1])+"\n"+

                                  str(authors[1][1])+"\n")

print("\nLevel 3 Publisher 1\t:"+str(authors[0][1][0]))

Output

 

RUN C:\Users\ACER ASPIRE\AppData\Local\Programs\Python\

                  Python35-32\Tools\scripts\listoflist.py

[['Programming in C#', ['Oxford University Press', 2015]],

        ['SE is everything', ['Obscure Publishers', 2015]]]

List:

['Programming in C#', ['Oxford University Press', 2015]]

['SE is everything', ['Obscure Publishers', 2015]]

Name of books

Programming in C#

SE is everything

Details of the books

['Oxford University Press', 2015]

['Obscure Publishers', 2015]

Level 3 Publisher 1      :Oxford University Press

>>>  

The following two illustrations handle the list of lists using nested loops. Kindly note the output and the corresponding mappings.

 

Illustration 4.12: Handling list of lists using loops

The elements of nested lists can also be dealt with using nested loops as shown in this illustration.

Program

 

hb=["Programming in C#",["Oxford University Press", 2015]]

rm=["SE is everything",["Obscure Publishers", 2015]

authors=[hb, rm]

print(authors)

for i in range(len(authors)):

   for j in range(len(authors[i])):

     print(str(i)+" "+str(j)+" "+str(authors[i][j])+"\n")

print()

>>>  

Output

 

RUN C:/Users/ACER ASPIRE/AppData/Local/Programs/Python/Python35-32/Tools/scripts/listfor.py

[['Programming in C#', ['Oxford University Press', 2015]], ['SE is everything', ['Obscure Publishers', 2015]]]

0 0 Programming in C#

0 1 ['Oxford University Press', 2015]

1 0 SE is everything

1 1 ['Obscure Publishers', 2015]

 

>>>  

 

Illustration 4.13

Another illustration of the use of loops in processing nested lists. The user is expected to observe the output and infer what happened.

Program

 

hb=["Programming in C#",["Oxford University Press", 2015]]

rm=["SE is everything",["Obscure Publishers", 2015]]

authors=[hb, rm]

print(authors)

for i in range(len(authors)):

   for j in range(len(authors[i])):

     for k in range(len(authors[i][j])):

       print(str(i)+" "+str(j)+" "+str(k)+"

   "+str(authors[i][j][k])+"\n")

print()

Output

 

RUN C:/Users/ACER ASPIRE/AppData/Local/Programs/Python/Python35-32/Tools/scripts/listfor.py

[['Programming in C#', ['Oxford University Press', 2015]], ['SE is everything', ['Obscure Publishers', 2015]]]

0 0 0 P

0 0 1 r

0 0 2 o

0 0 3 g

0 0 4 r

0 0 5 a

0 0 6 m

0 0 7 m

0 0 8 i

0 0 9 n

0 0 10 g

0 0 11

0 0 12 i

0 0 13 n

0 0 14

0 0 15 C

0 0 16 #

0 1 0 Oxford University Press

0 1 1 2015

1 0 0 S

1 0 1 E

1 0 2

1 0 3 i

1 0 4 s

1 0 5

1 0 6 e

1 0 7 v

1 0 8 e

1 0 9 r

1 0 10 y

1 0 11 t

1 0 12 h

1 0 13 i

1 0 14 n

1 0 15 g

1 1 0 Obscure Publishers

1 1 1 2015

 

4.5 POINTS TO REMEMBER

·         In order to repeat a set of statements a certain number of times looping is used.

·         Looping in Python can be implemented using while and for.

·         'while'  is the most common looping construct in Python.

·         The statements in the while block executes until the test condition remains true.

·         The else part executes if the loop ends without a break.

·         'for' can be used for all the purposes for which a 'while'  is used.

·         'for'  is generally used for processing lists, tuples, matrices, etc.

·         range (n)  means values from 0 to (n – 1).

·         range (m, n)  means all the values from m to (n – 1).

·         A loop can be nested in a loop.

·         There can be any number of nestings, although this is undesirable.

 

4.6 EXERCISES


MULTIPLE-CHOICE QUESTIONS

1.      What will be the output of the following?
a=8
i=1
while a:
 print(a)
 i=i+1
 a=a–i
print(i)

a.      8, 6, 3

b.      8, 6, 3, 1

c.       8, 6, 3, –1, ...

d.      None of the above

Answer:

(b)

2.      a=8
i=1
while a:
        print(a)
        i=i+1
        a=a/2
        print(i)

a.      8, 4, 2, 1

b.      8, 4, 2, 1, 0

c.       8, 4, 2, 1, 0.5

d.      Infinite loop

Answer:

(d)

3.      How many times will the following loop execute?
n = int(input('Enter number'))
i = n
while (i>0):
        print(n)
        i=i+1
        n = int(n/2)
        print(i)
#The value of n entered by the user is 10

a.      4

b.      5

c.       Infinite

d.      The code will not compile

Answer:

(c)

4.      Which loop can be used when the number of iterations is not known?

a.      while

b.      for

c.       both

d.      None of the above

Answer:

(c)

5.      How many levels of nesting are possible in for?

a.      2

b.      3

c.       Any number

d.      Depends on environment

Answer:

(d)

6.      n = int(input('Enter number'))
for i in (0,7):
print('i is '+str(i))
i = i+1;
else:
print('bye')
How many values would be printed?

a.      2

b.      3

c.       6

d.      None of the above

Answer:

(a)

7.      n = int(input('Enter number'))
for i in range(n, 1, -1):
for j in range(i):
print(i, j)
#value entered by the user is 5

a.      (5, 0), (5, 1), ...(2, 1)

b.      (5, 1), (5,2),...(2, 0)

c.       (0,1), (0,2), ...(5, 2)

d.      None of the above

Answer:

(d)

8.      In order to print the elements of a given matrix which of the following is essential?

a.      Nested loops

b.      Single loop

c.       if-else

d.      None of the above

Answer:

(a)

9.      What is meant by range (5) ?

a.      Integers from 0 to 4

b.      Integers from 0 to 5

c.       Integers from 1 to 4

d.      Integers from 1 to 5

Answer:

(a)

10. What is meant by range (3, 8) ?

a.      3, 4, 5, 6, 7, 8

b.      3, 4, 5, 6, 7

c.       1, 2, 4, 5, 6, 7, 8

d.      8, 8, 8

Answer:

(b)

 

4.7 PROGRAMMING

1.      Ask the user to enter a number and find whether it is a prime number.

2.      Ask the user to enter a number and find all its factors.

3.      Find whether the number entered by the user is a perfect square.
Example: If number = 30, then factors are 2, 3, and 5

4.      Ask the user to enter two numbers and find the lowest common multiple. Example: If numbers are 30 and 20, then LCM is 60, as both 20 and 30 are factors of 60

5.      Ask the user to enter two numbers and find the highest common factor. Example: If numbers are 30 and 20, the HCF is 10

6.      Find the mean of numbers entered by the user.



7. Find the variance and standard deviation of the numbers entered by the user.

8.  Ask the user to enter the values of a and b and find aba.

9.  Find the common factor of n numbers entered by a user.

10. Ask the user to enter three numbers and find all possible permutations of these numbers.

11. In the above question, what happens if we have four numbers in place of three?

12. Can the above logic be extended for n numbers?

13. Ask the user to enter n numbers and find the minimum of the numbers without using arrays.

14. Ask the user to enter n numbers and find the maximum of the numbers without using arrays.

15. Create a list of authors in which the record of each author is itself a list consisting of the name of the book, publisher, year of publication, ISSN, and the city. Now process the list using for  loop.