John Long Silver
John Long Silver

Reputation: 51

Backwards looping, creating a diamond pattern

I made a program that allows the user to type in the height of a diamond and it will print one out in asterisks using loops. My code now looks like this:

diamond = int(input("Height": )

for i in range(diamond-1):
    print((diamond-i) * " " + (2*i+1) * "*")
for i in range(diamond-1, -1, -1):
    print((diamond - i) * " " + (2 * i + 1) * "*")

And the diamond will look perfect like this (diamond == 6):

      *
     ***
    *****
   *******
  *********
 ***********
  *********
   *******
    *****
     ***
      *

Now if I make some changes and instead write the backwards loop like this:

for i in reversed(range(diamond-1)):
    print((diamond - i) * " " + (2 * i + 1) * "*")

It will print out the diamond like this:

      *
     ***
    *****
   *******
  *********
  *********
   *******
    *****
     ***
      *

So my question is: what is the difference between the first backwards loop and the second one I wrote? Why do they turn out so different?

Upvotes: 4

Views: 246

Answers (1)

wim
wim

Reputation: 363043

Because they are different ranges:

>>> diamond = 6
>>> range(diamond-1, -1, -1)
[5, 4, 3, 2, 1, 0]
>>> list(reversed(range(diamond-1)))
[4, 3, 2, 1, 0]

range includes the start point, but excludes the end point.

Upvotes: 3

Related Questions