KnowledgeBoat Logo

Computer Science

How many times will the following for loop execute and what's the output?

for i in range(1,3,1):
    for j in range(i+1):
        print('*')

Python

Python Funda

27 Likes

Answer

Loop executes for 5 times.

*
*
*
*
*

Working

range(1,3,1) returns [1, 2]. For first iteration of outer loop j is in range [0, 1] so inner loop executes twice. For second iteration of outer loop j is in range [0, 1, 2] so inner loop executes 3 times. This makes the total number of loop executions as 2 + 3 = 5.

Answered By

11 Likes


Related Questions