Search code examples
pythonfor-loopnested-loops

Python counting in nested forloops


I'm brand new to python and have an assignment to "Use two nested for loops. Count up in the outer for loop from 0 to 9 and then at every step count back down to zero."

The answer is supposed to be this:

i= 0
k= 0
i= 1
k= 1
k= 0
i= 2
k= 2
k= 1
k= 0
i= 3
k= 3
k= 2
k= 1
k= 0
i= 4
k= 4
k= 3
k= 2
k= 1
k= 0
i= 5
k= 5
k= 4
k= 3
k= 2
k= 1
k= 0
i= 6
k= 6
k= 5
k= 4
k= 3
k= 2
k= 1
k= 0
i= 7
k= 7
k= 6
k= 5
k= 4
k= 3
k= 2
k= 1
k= 0
i= 8
k= 8
k= 7
k= 6
k= 5
k= 4
k= 3
k= 2
k= 1
k= 0
i= 9
k= 9
k= 8
k= 7
k= 6
k= 5
k= 4
k= 3
k= 2
k= 1
k= 0

So every time the i counts up, k counts down starting from the previous value of i. I believe I understand the general concept of nested forloops, but I'm not sure if my problem lies in identifying the range for k or in printing i and/or k. Here's what I have:

for i in range(0,10):
for k in range(i+1):
    print 'i=',i,''
    print 'k=',k,''

But it doesn't give me what I need. It seems like k is going up when I run it, probably because of the (i+1) but it's the closest answer I've gotten so far and I've been having a fair amount of trouble. I'm not looking for the answer itself, but if someone could point me in the right direction that would be very helpful. Thanks!


Solution

  • You just need your second for loop to go backwards instead of forwards. Right now it is going from 0 to i.

    The syntax for this is:

    for k in range(i, -1, -1):
    

    This starts k at i, until k is not -1, applying -1 to it in each iteration.

    So your complete program would be:

    for i in range(0,10):
        print 'i=',i,''
        for k in range(i, -1, -1):
            print 'k=',k,''
    

    Output:

    i= 0
    k= 0
    i= 1
    k= 1
    k= 0
    i= 2
    k= 2
    k= 1
    k= 0
    i= 3
    k= 3
    k= 2
    k= 1
    k= 0
    i= 4
    k= 4
    k= 3
    k= 2
    k= 1
    k= 0
    i= 5
    k= 5
    k= 4
    k= 3
    k= 2
    k= 1
    k= 0
    i= 6
    k= 6
    k= 5
    k= 4
    k= 3
    k= 2
    k= 1
    k= 0
    i= 7
    k= 7
    k= 6
    k= 5
    k= 4
    k= 3
    k= 2
    k= 1
    k= 0
    i= 8
    k= 8
    k= 7
    k= 6
    k= 5
    k= 4
    k= 3
    k= 2
    k= 1
    k= 0
    i= 9
    k= 9
    k= 8
    k= 7
    k= 6
    k= 5
    k= 4
    k= 3
    k= 2
    k= 1
    k= 0