NESTED LOOP

M3-R5.1 · Chapter 4: Operators, Expressions and Python Statements · 3 min read

Nested Loop in Python

A loop inside another loop is known as nested loop. In nested loop , the inner loop must terminate before the ending of the outer loop   
   OR

A nested loop in Python refers to a loop inside another loop. This structure allows you to iterate over multi-dimensional data, such as lists of lists or matrices. Each iteration of the outer loop triggers a complete cycle of the inner loop

Nested while Loop : The while loop having one or more inner while loops are nested while loop.

Syntax:

while expression:

        while expression:

              statement(s)

        statement(s)

Example 1:

i = 1

while i <=10:

    j = 1

    while j <=10:

        print(i*j,end="\t")

        j = j + 1

    print("")

    i = i + 1

print("Complete!")

Example 2:

i = 1

while i <= 3:  # Outer loop

    j = 1

    while j <= 2:  # Inner loop

        print(f"Outer loop {i}, Inner loop {j}")

        j += 1

    i += 1

In this example, the outer loop runs three times (i from 1 to 3), and inside each iteration, the inner loop runs twice (j from 1 to 2). So overall, the inner loop executes 3 × 2 = 6 times.

rows = 5

i = 1

while i <= rows:  # Outer loop

    j = 1

    while j <= i:  # Inner loop

        print("*", end=" ")

        j += 1

    print()  # Move to the next line

    i += 1

*

* *

* * *

* * * *

* * * * *

The outer loop (i) controls the number of rows.

  • The inner loop (j) controls how many stars (*) are printed per row.

The end=" " ensures the stars stay on the same line, while print() moves to the next row

x=10

while x>1:

    y=10

    while y>=x:

       print(x, end="")

       y-=1

    x-=1

    print("")

Nested for Loop: The for loop having one or more inner for loops is nested for loop.

Basic Syntax:

for var in sequence:

         for var1 in sequence:

                     statements(s)

          statements(s)

for i in range(a):

            for j in range(b):

                        statement of j loop

            statement of i loop

Example: