Table of Contents

Python Nested For Loops – Iteration and Looping

Example Description
Learn how to use nested for loops in Python. Understand the logic, see the code output, explore different iterations of the outer/inner loops

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:

  1. The code starts with an outer loop that iterates three times.
  2. In each iteration, it prints the current iteration number.
  3. Inside the outer loop, there is a nested inner loop that iterates twice.
  4. In each iteration of the inner loop, it prints the current iteration number.
  5. After each inner loop iteration, it prints “Out of inner loop”.
  6. Once all iterations of the inner loop are completed, it continues to the next iteration of the outer loop.
  7. 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