CBSE Class 12 Computer Science Question 92 of 105

Python Revision Tour — Question 18

Back to all questions
18
Question

Question 4(ii)

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('*')
Answer

Loop executes for 5 times.

Output
*
*
*
*
*
Explanation

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.