I have doubt in these python nested for loop, that how the inner loop is executing can anyone resolve my problem here
JavaScript
x
5
1
for i in range(1, 4):
2
print(i)
3
for j in range(1, i):
4
print(j)
5
Advertisement
Answer
Basically, your for
loops are counting numbers from 1 to the upper limit minus 1.
Your code will run as follows:
Starting with i=1
, it will print out a 1
and then j
will go from 1
to 0
, that is it will take up no values and j
won’t be printed.
Next, i
will become 2
, and then j
will go from 1
to 2
, resulting in the output 1
from j
.
This will continue, and the overall output will be:
JavaScript
1
7
1
(i)1
2
(i)2
3
(j)1
4
(i)3
5
(j)1
6
(j)2
7
The stuff in the brackets show which variable is being printed.