Introduction:
This Python code demonstrates the use of nested for loops to perform iterations and looping. The code includes an outer loop and an inner loop, showcasing the logic of how they work together to execute a series of print statements. The output of the code is provided to help understand the flow of the loops.
Code:
#Demonstrate working of nested for loops
for var1 in range(3):
print( "Iteration " + str(var1 + 1) + " of outer loop")
for var2 in range(2): #nested loop
print(var2 + 1)
print("Out of inner loop")
print("Out of outer loop")
Logic:
- The code starts with an outer loop that iterates three times.
- In each iteration, it prints the current iteration number.
- Inside the outer loop, there is a nested inner loop that iterates twice.
- In each iteration of the inner loop, it prints the current iteration number.
- After each inner loop iteration, it prints “Out of inner loop”.
- Once all iterations of the inner loop are completed, it continues to the next iteration of the outer loop.
- After all iterations of both the outer and inner loops are completed, it prints “Out of outer loop”.
Output:
>> Iteration 1 of outer loop
>> 1
>> 2
>> Out of inner loop
>> Iteration 2 of outer loop
>> 1
>> 2
>> Out of inner loop
>> Iteration 3 of outer loop
>> 1
>> 2
>> Out of inner loop
>> Out of outer loop