Conditional Constructs and Looping

Nested Loops

When we wish to have some statements for executing a hundred times, we do not repeat them 100 times. Suppose you wish to print numbers 1 to 99 or wish to greet your 99 friends. In this case, you can make use of loops in Python. The four types of Python Loops are Python For Loop, Python While Loop, Python Loop Control Statements and Nested Loops in Python.

nested loops

Python Nested Loops

These are basically loops inside loops. In other words, a nested loop refers to a loop inside a loop. The “inner loop” will execute one time for each iteration of the “outer loop”:

Example

                    

Print each adjective for every vegetable:

adj = ["green", "leafy", "juicy"]

vegetables = ["spinach", "kale", "pumpkin"]

for x in adj:

for y in vegetables:

print(x, y)

Python programming language enables us to use one loop inside another loop. To help you better understand the concept, please look at the examples given below:

Syntax

for iterating_var in sequence:

for iterating_var in sequence:

statements(s)

statements(s)

The syntax for a nested while loop statement in the Python programming language is given below:

while expression:

while expression:

statement(s)

statement(s)

A final note on loop nesting is that one can put any kind of loop inside of any other kind of loop. For instance, a for loop can be inside a while loop or vice versa.

Example

The program given below makes use of a nested for loop to find the prime numbers from 2 to 100 −

                    

i = 2

while(i < 100):

j = 2

while(j <= (i/j)):

if not(i%j): break

j = j + 1

if (j > i/j) : print i, " is prime"

i = i + 1

print "The End!"

When the above code executes, it forms the result given below:

                    

2 is prime

3 is prime

5 is prime

7 is prime

11 is prime

13 is prime

17 is prime

19 is prime

23 is prime

29 is prime

31 is prime

37 is prime

41 is prime

43 is prime

47 is prime

53 is prime

59 is prime

61 is prime

67 is prime

71 is prime

73 is prime

79 is prime

83 is prime

89 is prime

97 is prime

The End!

Browse more Topics Under Conditional Constructs and Looping

Nested Loops

We will now discuss more nested loops in python.

1) Nested for loop Syntax

The basic syntax of a nested for loop in Python is:

for [iterating_variable_1] in [sequence_1]: #Outer Loop
for [iterating_variable_2] in [iterating_variable_1/sequence_2]: #Inner Loop
[code to execute]

Example:

                    

for i in range(11):               #line 1
for j in range(i):            #line 2
print('*', end='')        #line 3
print('')                     #line 4

Output:

                    

*

**

***

****

*****

******

*******

********

*********

**********

Execution Flow

In the program, the use of two iteration variables i and j have been made to print a pattern of stars. The compiler starts with line 1. It encounters a for loop and a range function. Moreover, the range function in Python outputs an iterable range of integer numbers from 0 to the number stated in the argument. The argument number then gets excluded from the array.

In our case, it will produce an array [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. At this instant, the compiler is aware that it must execute the next set of statements 10 times. When it will move to line 2, it will encounter another for loop and range function.

Kindly note that the argument to this range function is a computed value of our iteration variable i. Consequently, it dynamically produces an array liable to the value of i. When i=0, the array is empty. When i=1, array is [0]. When i=2, the array is [0, 1] and so forth.

Therefore, the number of times line 3 executes directly is dependent on the value of i. Observe the part end=’’ inline 3. It is for preventing Python from printing a linefeed after every star. We only require a linefeed at the end of every iteration of the outer loop. Therefore, we explicitly print a linefeed in line 4 of our code. We will now assess every iteration of our nested for loop.

                    

Outer Loop Iteration 1

I = 0, j = [], output is a blank line.

Outer Loop Iteration 2

I = 1, j = [0], output = *

Outer Loop Iteration 3

I = 2, j = [0, 1], output = **

Outer Loop Iteration 4

I = 3, j = [0, 1, 2], output = ***

.
.
.

Outer Loop Iteration 10

I = 9, j = [0, 1, 2, 3, 4, 5, 6, 7, 8], output = *********

Outer Loop Iteration 11

I = 10, j = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], output = **********

2) Nested While Loop

Syntax

The syntax for nesting while loop in Python is:

while (expression_1):             #Outer loop
[code to execute]          #Optional
while (expression_2):      #Inner loop
[code to execute]

Dissimilar to the for loop, the while loop does not have a precompiled iterable sequence. While loop will keep on executing the code until the expression evaluates to true. Consequently, a developer has to always remember to update the iterating variable/expression. If not, the loop will enter infinite execution mode.

Example

                    

i=1                        #line 1
while(i<=5):               #line 2
j=5                    #line 3
while(j>=i):           #line 4
print(j, end=' ')  #line 5
j-=1               #line 6
i+=1                   #line 7
print()                #line 8

Output:

                    

5 4 3 2 1

5 4 3 2

5 4 3

5 4

5

Execution Flow

Line 1 of the code sets the outer loop’s iterating variable to the initial value. After that, the next line is the beginning of the outer while loop. It has an expression i<=5. This expression gets assessed for true value after each iteration. Further, the execution moves in the loop only if the condition is true. Meaning to say, as soon as the condition becomes false, the loop gets terminated.

As the initial value of I is 1, the condition in line 2 is true. Thus, the compiler moves to line 3 and sets our inner loop’s iterating variable j to 5. Line 4 once more has a while loop with an expression that evaluates to true. Therefore, the compiler will execute line 5 and 6. It will then moves back to line 4 and assess the condition.

If the condition is true, it will once more enter line 5 and 6. If the condition turns false, the loop will terminate and the next lines to be executed are line 7 and 8. The same thing follows for the outer loop.

Line 6 and 7 are very vital as they update our iterating variable. Without them, the program flow would enter infinite execution mode as the while loop expressions will always result in truthy.

FAQ on Nested Loops

Question 1: What are nested loops with an example?

Answer 1: A nested loop refers to a loop within a loop, an inner loop within the body of an outer one. Further, the first pass of the outer loop will trigger the inner loop, which will execute to completion. After that, the second pass of the outer loop will trigger the inner loop again.

Question 2: How does a nested while loop work?

Answer 2: A nested while loop is basically a while statement inside another while statement. In a nested while loop, one iteration of the outer loop first executes, after which the inner loop executes. When the condition of the inner loop gets satisfied, the program moves to the next iteration of the outer loop.

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

avatar
  Subscribe  
Notify of

Customize your course in 30 seconds

Which class are you in?
No thanks.