KnowledgeBoat Logo
LoginJOIN NOW

Computer Science

What is nested loop? Explain with example.

Python Control Flow

2 Likes

Answer

A loop may contain another loop as a part of its body. This loop inside a loop is called a nested loop. Once the condition of outer loop is true, the control is transferred to the inner loop. The inner loop is terminated first and then the outer loop terminates.

For example,

for i in range(1, 4):
    for j in range(1, i+1):
        print(j, end = '')
    print()
Output
1
12
123

Here, range function will generate value 1, 2, 3 in the outer loop. The inner loop will run for each value of i used in outer loop. The value of outer loop variable will change only after the inner loop completely terminates.

Answered By

2 Likes


Related Questions