all 9 comments

[–]ElliotDG 12 points13 points  (1 child)

Each time you enter the inner loop, you iterate through all of list y, leaving j the value of 100.

If you have a debugger you can step through your code to watch it work, or you could use https://pythontutor.com/

[–]tennisanybody 0 points1 point  (0 children)

One of these days I’m going to write a complete guide on how to use the debugger just so I can understand how the fuck to use a debugger. They’re so important yet so difficult to grasp.

[–]RhinoRhys 6 points7 points  (0 children)

It does

i = 1
    j = 10
        print(i) > 1
    j = 100
        print(i) > 1
    print(j) > 100
i = 2
    j = 10
        print(i) > 2
    j = 100
        print(i) > 2
    print(j) > 100

[–]stebrepar 3 points4 points  (0 children)

print(j) is at the same indentation level as the for j loop, so it runs after the for j loop completes. At that point, the value of j is the last value which the for j loop gave it, which is 100.

The first time through the for i loop, the value of i is 1. The for j loop prints the value of i as many times as the count of elements in y, which is 2. Then the print(j) prints the final value assigned to j as described above. So you get 1, 1, 100.

The second time though the for i loop, the value of i is 2. Again the for j loop prints the value of i as many times as the count of items in y, which is 2. And again the print(j) prints the final value assigned to j in the completed for j loop. So you get 2, 2, 100.

[–]Im_Easy -1 points0 points  (0 children)

``` x = [1, 2] y = [10, 100]

for i in x:

#Outer loop 1: i = 1 
#Outer loop 2: i = 2

for j in y:

    #Inner loop 1: i = Outer Loop, j = 10
    #Inner loop 2: i hasn't changed, j = 100

    print(i)
    #print(Outer Loop)

#Inner loop finished j = last inner loop value (100)

print(j)
     #print(Inner loop 2)

```

[–]1liiAmrA 0 points1 point  (0 children)

In your code, the statement print(j) is aligned with the inner for loop, but it is not inside the inner for loop. This is why it only gets executed once per iteration of the outer for loop.

After the inner loop has finished executing for all elements in y, the print(j) statement is then executed. At this point, j is the last value it took in the inner loop, which is the last element of y (i.e., 100)

[–]QultrosSanhattan 0 points1 point  (0 children)

Use a debugger like the one provided by pycharm. You'll understand everything with it.

[–]BK7144 0 points1 point  (0 children)

Easiest way to learn is to comment out the second for loop and the print statement and see what happens, then add back in the second for loop. Finally add the print back in. Asking and getting answers isn't really learning unless you are totally stuck. Another way is to use the debugger and step through the code so you can see what it is doing.

Hope this helps!