Introduction to Python Nested Loops
Welcome to another chapter in the Python learning course – Nested Loops. A great way to loop a loop, nested loops have proved their worth in every programming language. Today, we will be focusing on Python specifically – the types, the syntax, and the examples. So, let’s get started.
Nested Loops
It would be good to briefly touch base upon Nested Loops in general before proceeding with Python specifically. If a loop exists inside the body of another loop, it is termed as Nested Loop. This means that we want to execute the inner loop code multiple times. The outer loop controls how many iterations the inner loop will undergo. A basic example of a nested for loop is:
for (i=0; i<10; i++)
{
for (j=0; j<10; j++)
{
//This code will execute 100 times.
}
//This code will execute 10 times.
}
A thing to note here is that any type of loop can be nested inside another loop. For example, a while loop can be nested inside a for loop or vice versa.
Python Nested Loops
Let us discuss more about 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
Let’s try to understand the execution flow of the above program. In the program, we used two iteration variables, i and j, to print a pattern of stars.
The compiler begins with line 1. It encounters a for loop and a range function. Python’s range function outputs an iterable array of integer numbers from 0 to the number specified in the argument. The argument number is excluded from the array. In our case, it will generate an array [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. Now, the compiler knows it must execute the next set of statements 10 times.
When it moves to line 2, it encounters another for loop and range function. Note that the argument to this range function is a computed value of our iteration variable i. So, it dynamically generates an array depending on 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 on.
So, the number of times line 3 is executed directly depends on the value of i. Notice the part end=’’ inline 3. This is to prevent Python print a linefeed after every star. We only want a linefeed at the end of every iteration of the outer loop. Thus, we have explicitly printed a linefeed in line 4 of our code.
So now, let us closely examine 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]
Unlike the for loop, the while loop doesn’t have a precompiled iterable sequence. While loop keeps executing the code until the expression evaluates to true. So, a developer has to always keep in mind to update the iterating variable/expression, or else 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:
Execution Flow
Line 1 of the code sets the outer loop’s iterating variable to the initial value. The next line is the beginning of the outer while loop. It has an expression I <=5. This expression is evaluated for true value after each iteration. The execution enters the loop only if the condition is true. As soon as the condition becomes false, the loop is terminated.
Since the initial value of I is 1, the condition in line 2 is true. So, the compiler moves to line 3 and sets our inner loop’s iterating variable j to 5. Line 4 again has a while loop with an expression that evaluates to true. So, the compiler executes line 5 and 6. It then moves back to line 4 and evaluates the condition. If the condition is true, it again enters line 5 and 6. If the condition becomes false, the loop is terminated, and the next lines to execute are line 7 and 8. The same is followed for the outer loop.
Line 6 and 7 are very important as they update our iterating variable. Without them, the program flow would enter infinite execution mode as the while loop expressions would always result in truthy.
Should I break, continue or pass
As with almost all other programming languages, Python has the concept of break and continues. These keywords help terminate any loop or skip a particular iteration of the loop. Python also has another keyword – pass. Let’s take a look at these.
1) Break
The break keyword indicates the compiler to jump out of a loop and terminate its execution.
Example
for i in range(5):
for j in range(5):
if i == j:
break
print(j, end='')
print('')
Output:
The program above breaks the inner for loop if the value of I and j are equal. It does not execute further iterations of the loop. This can be further understood with the continue statement.
2) Continue
The continue keyword indicates the compiler to skip the current iteration of the loop and continue with the next iteration.
Example
for i in range(5):
for j in range(5):
if i == j:
continue
print(j, end='')
print('')
Output:
Notice that the same program, but with a continue statement instead of break, does not terminate the loop execution. It only skips the current iteration.
3) Pass
The pass keyword is interesting in Python. It simply means do nothing. It is used when the code block is needed syntactically, but you do not want any command to be executed. It simply acts as a placeholder.
Example
for i in range(5):
for j in range(5):
if i == j:
#I am not sure what to do when i equals j, so for now I will pass.
pass
print(j, end='')
print('')
Output:
Conclusion
Loops are strategically very important to learn to perform a task with minimal lines of code. This is just a basic introduction to loops. It is recommended to play around more, get creative and explore the potential of loops further.
Recommended Articles
We hope that this EDUCBA information on “Perl print hash” was beneficial to you. You can view EDUCBA’s recommended articles for more information.