Python counting in nested forloops
<p>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."</p>

<p>The answer is supposed to be this:</p>

<pre><code>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
</code></pre>

<p>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:</p>

<pre><code>for i in range(0,10):
for k in range(i+1):
    print 'i=',i,''
    print 'k=',k,''
</code></pre>

<p>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!</p>

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

<p>The syntax for this is:</p>

<pre><code>for k in range(i, -1, -1):
</code></pre>

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

<p>So your complete program would be:</p>

<pre><code>for i in range(0,10):
    print 'i=',i,''
    for k in range(i, -1, -1):
        print 'k=',k,''
</code></pre>

<p>Output:</p>

<pre><code>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
</code></pre>

python for-loop nested-loops