Skip to content
Advertisement

Can anyone explain these python nested loop please

I have doubt in these python nested for loop, that how the inner loop is executing can anyone resolve my problem here

for i in range(1, 4):
    print(i)
    for j in range(1, i):
        print(j)

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:

(i)1
(i)2
(j)1
(i)3
(j)1
(j)2

The stuff in the brackets show which variable is being printed.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement