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
Which of the following is the correct output for the execution of the following Python statement ?
print(5 + 3 ** 2 / 2)
- 32
- 8.0
- 9.5
- 32.0
How many times will the following for loop execute and what's the output?
for i in range(-1, 7, -2): for j in range (3): print(1, j)
Find and write the output of the following python code:
for Name in ['Jay', 'Riya', 'Tanu', 'Anil'] : print (Name) if Name[0] == 'T' : break else : print ('Finished!') print ('Got it!')
Is the loop in the code below infinite? How do you know (for sure) before you run it?
m = 3 n = 5 while n < 10: m = n - 1 n = 2 * n - m print(n, m)