Search code examples
pythonnested-for-loop

Nested For Loop - A problem with understanding the concept


Welcome

I generally understand the concept of loops and how they work. Yet, I have encountered one that I just cannot comprehend

for i in range(10):
    for j in range(i):
        print(i, end="")
print()

This loop will display a list of numbers

1
22
333
4444
55555
666666
7777777
88888888
999999999

Which is exactly what i wanted... But i cannot understand why does it print the same numbers in each line. If the "j" variable is printed the program act like i expectd it to work.

0
01
012
0123
01234
012345
0123456
01234567
012345678

Does anybody have any idea why that is?

Edit:

Thank you for the answers. I finally get it(and feel so stupid that I haven't before)


Solution

  • The same character is repeated because the second for loop is printing i, the value from the outer loop. If it was printing j it would look how you expect. The value of i only changes once the j loop finishes. An outer loop won't repeat until any inner loops are done.

    If this wasn't obvious to you even after you printed j, then it seems like your knowledge of for loops is lacking something fundamental. You would greatly benefit from learning to use a debugger, which is critical day 1 knowledge for any software engineer.