-3

Here is my code

    for j in range(5,8):
        for i in range(6):
            print("[{}][{}]".format(i,j))
            j-=1

This is what I am getting. The j value on the right should decrement from 5 to 4 after the first complete loop. View code for further explanation

    [0][5]
    [1][4]
    [2][3]
    [3][2]
    [4][1]
    [5][0]

    [0][6] # Here, I want the j value or 6 to decrement to 4 but it's incrementing
    [1][5]
    [2][4]
    [3][3]
    [4][2]
    [5][1]

    [0][7]
    [1][6]
    [2][5]
    [3][4]
    [4][3]
    [5][2]

This is what I want

    [0][5]
    [1][4]
    [2][3]
    [3][2]
    [4][1]
    [5][0]

    [0][4] # Here, I want the j value to decrement to 4  
    [1][3]
    [2][2]
    [3][1]
    [4][0]

    [0][3]
    [1][2]
    [2][1]
    [3][0]

3 Answers3

1

Without knowing what it is you're actually trying to accomplish, it's a little hard to answer.

However, this should work:

for i in range(6, 3, -1):
    for j in range(i):
        print("[{}][{}]".format(j, i-j-1))
    print
chukrum47
  • 81
  • 3
  • The 'i' and J can't be swapped around. It has to be 'i' then 'j' – user7401490 Jan 19 '17 at 19:37
  • Then go ahead and swap the i's and j's in the code I listed for you: their order makes no difference (although it is custom to use i for the outer loop and j for the inner one). – chukrum47 Jan 19 '17 at 20:42
0

I would hazard a guess that when you return to external loop statement, j receives its value from range generator - as it should, overwriting meaningless manipulations.

And since value of i (one more reason to hate one-letter variable names) returns to 0 - again, by loop - and j is incremented to 6, the result is obvious.

volcano
  • 3,578
  • 21
  • 28
0

You should never modify a loop variable this way. I think every new loop resets the variable. It seems you want sort of combination of two numerical numbers. Use itertools instead.

https://docs.python.org/3/library/itertools.html

Bobby
  • 1,511
  • 1
  • 15
  • 24