Home > Net >  Can anyone explain these python nested loop please
Can anyone explain these python nested loop please

Time:03-22

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)

CodePudding user response:

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.

CodePudding user response:

For one your code example is poorly formatted. I am assuming this is how the code is.

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

This is a very simple for loop example, I'll go over two iterations that should make it clear.
Let's look at the outer for loop, it goes from 1 to 3 (4 exclusive)

i=1 now, j will go from 1 to i i.e. 1 to 1.
The inner loop will now look as follows:

..
  for j in range(1, 1):
    print(j)

As range(1, 1), 1 will be exclusive, hence this loop will not run. So out of Iteration 1:

1 # print(i)

=====
i=2, now, j will go from 1 to i i.e. 1 to 2. outer loop will print 2, and now inner loop will look like:

..
  for j in range(1, 2):
    print(j)

This will print 1, as 2 is excluded limit.
Now output will be

2 # outer loop
1 # Inner loop.

On similar retrospection, the last iteration at i=3
Will give output:

3 # outer loop print(i)
1 # inner loop print(j)
2 # inner loop print(j)

Combining all three the final output would be

1 # outer
2 # outer
1 # inner
3 # outer
1 # inner
2 # inner
  • Related