Firstly, just wanted to point out, your code does not print out the entire pyramid; it only prints half of it out. Your output should something like (if we input height to be 3, for example):
# #
## ##
### ###
Your code only prints the left side:
#
##
###
Now, to your question. Here is how you got it to work:
for i in range(h):
print(" " * (h - i) + "#" * (i + 1));
To describe the conditional statement of the for-loop, i
starts at 0, and it goes up till h
.
To understand how your print()
statement works, think of it as a line segment that consists of spaces and hashes. The length of this segment is h
. So, in h - i
, you print part of this "segment" as spaces, and in i + 1
, you print the remainder of the loop.
Now, the reason you use i + 1
, and not just i
is because of the for-loop condition; i
starts at zero. As a result, you must have realized that the first line has no hashes, as there is h - 0
spaces, and 0
hashes. That is why the i + 1
was required; you are printing an extra space at the start of every line, if you check closely with your current code.
A more easier-to-understand logic of your code, with the same results, is:
for i in range(1, h + 1): # The counter's range is toyed with here
print(" " * (h - i) + "#" * i); # The "i + 1" is removed
Here, the range of the loop is toyed with; now it starts at 1 (so that the first hash is printed, and the entire "segment" is not only spaces in the first line), and it ends at h + 1
(so that the range of the loop stays the same).
The i + 1
is removed; seeing the print()
statement makes it easier to understand the "segment" logic discussed above.
*Just to clarify, the alternate code I provided above is not intended as a replacement to your code; I just included it to reinforce my "segment" idea. Your code is perfectly fine and works just as well as mine.