Python Data Presistence – Nested Loops

Python Data Presistence – Nested Loops

Nesting is a very popular term in programming parlance. It indicates the existence of a certain entity inside another that is of the same type. If you have a situation where an if statement appears inside another if statement, it is termed as nested if. Similarly, a loop within another loop constitutes nested loops. It is also possible to have nested functions, classes, and so on. We are going to discuss nested loops here.
As mentioned above, a nested loop means the existence of a loop within a loop. The following diagram illustrates the situation (figure 2.19):

Python Data Presistence - Nested Loops chapter 2 img 1

What happens when such nesting of the loop is done? Each repetition of the outer loop encounters the inner loop which has to complete its own repetitions before the next round of the outer loop starts. As a result, if the outer loop is designed to perform m iterations and the inner loop is designed to perform n iterations, the innermost statement will be executed men times.

There are a number of instances around us where looping activities are performed in a nested manner. The clock for example has three loops. Outer loop counting hours has a nested loop for minutes, which in turn has a seconds loop.

Any type of loop (while or for) can appear in any other type. However, in practice, we find nesting for loops. The following example displays all prime numbers between 1 and 100. Outer loop iterates over a range object. Inner loop checks whether each number in the outer range is prime or not.

Example

#nestedfor.py
for num in range ( 1 , 101):
for x in range(2,num):
if num%x==0:
break
x=x+1
else:
print (num,sep=’ ‘, end = ‘ ‘ )

Output:

E:\python37>python nestedfor.py
1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 93 59 61 67 71 73 79 83 89 97
E:\python37>