Search code examples
pythonfor-loopnested-loops

When using a for loop range with an increment of three, why does the first number 'group' to itself?


We are using the following book in a class I am TA-ing for: craftbuzzcoder. In Part 3 (Loop), section Wall & cube, they have a challenge of creating an inverted pyramid.

The following is the book solution:

for j in range(0,10,3): 
    for i in range (-j, j+1, 3):
        for k in range(-j, j+1, 3):
            game.set_block(Position(i, j+1, k), 45)

From what I can tell, it seems to be that the first number in the sequence of the respective range (for example, the y-axis/j variable) is counted/grouped by itself rather than by the increment of 3.

Why is this?

tl;dr I would expect it to increment like this: enter image description here

Instead it seems to be increment like this: enter image description here

Why?


Solution

  • You need to understand how python range works and this will become easier for you.

    range(start, stop[, step])

    start is from where you want to start the iteration

    stop is at where you want to stop the iteration, exclusive

    step means how much you want to add to start

    but there is a small catch with this, if step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero and step defaults to 1

    So in your case it is working like -

    for j in range(0,10,3):
        print j
    

    We get -

    j = 0 -> add 3, j becomes 3 -> add 3, j becomes 6 -> add 3, j becomes 9, add 3, j becomes 12  which is greater than stop -> exit
    

    More examples of range.