How to get a triangle of O’s

Here’s a function to do it:

def text_triangle(base, char):
    return '\n'.join(' ' * (base-i) + char * i for i in range(1, base+1))

print(text_triangle(6, 'o'))

Not going to hold the fact that you just posted a screenshot against you because this question has a lot to do with formatting, which is difficult to represent in markdown.


You got the correct number of spaces on each line (good job!). The problem with your code was that you were only putting a single 'o' on each line instead of filling the rest of the line with 'o'‘s.

base = 6
for r in range(base-1, -1, -1):
    for blank in range(0, r):
        print(' ', end='')
    for o in range(r, base):
        print('o', end='')

To do that, we can just write another nested for-loop that picks up where the last nested for-loop left off, at r, and go until the end of the line, base. Finally, we need to call print() with no arguments at the bottom of the main for-loop to get a newline character. I hope this is more explanatory than my quick answer before.

The above fits your teacher’s requirements, but is far from the best solution. If I had to answer this question without any restrictions (i.e. using nested for-loops), I would probably do something like this:

base = 6
for r in range(base):
    print('{:>{}}'.format('o' * (r+1), base))

This solution uses str.format() and the format specification mini-language to right align the 'o'‘s.

Browse More Popular Posts

Leave a Comment