Skip to content Skip to sidebar Skip to footer

How To Print A Triangle Using For Loops

I need some help trying to solve this, right now it keeps printing vertically only height = int(input('Height of triangle: ')) for x in range(height): for y in range(height):

Solution 1:

Here's my solution, it involves the use an of accumulator:

height = int(input("Height of triangle: "))
count = 0

for i in range(height-1):
    print('#' + ' '*count + '#')
    count += 1

print('#'*height)

Solution 2:

height = 6

for rowIndex in xrange(height-1):
    row = [' ']*height            # yields array of size height
    row[0] = row[rowIndex+1] = '#'
    print (''.join(row))    # This makes string from array
print ('#'*height)          # Print lower side of triangle

You can also remove "+1" on line 5 to get more "edgy" triangles.


Post a Comment for "How To Print A Triangle Using For Loops"