Alex Alex - 3 years ago 304
Python Question

Nested loop output confusion

for i in range(2):
for j in range(2):
print(i, j, end='')


Hey guys so im just having problems understanding this concept of nested loops.
The output when I run the program is: 0 00 11 01 1

I cant figure out why the output is the way it is. Could anybody give me a step by step explanation of the order in which this is executed?

Thanks

Answer Source

You have two loops in your program. One is outer and another one is inner loop. So this is how code is working. First of all following code is executed

for i in range(2):

This puts value 0 in i. Now it enters to inner loop. So following code is executed

for j in range(2):

This puts value 0 in j. Now the following code executes

print(i,j,end='')

This gives the output as i and j both have 0 value.

0 0

In programming language inner loop are completed first. So following code will execute again

for j in range(2):

This will set value of j as 1

Now j is 1 and i is still 0 So output will look like

0 00 1

(Note: first 0 0 is the previous output)

Now the following code is finished

for j in range(2):

Its finished at j's value 1 because range(2) means value will start from 0 to 1.

Now the following code will execute.

for i in range(2):

and i value will become 1.

Now the inner loop will run again.

for j in range(2):

This will set value of j again 0 and in the next iteration 1.

So the final output looks like

0 00 11 01 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download