'4.16 LAB: Warm up: Drawing a right triangle

This program will output a right triangle based on user specified height triangle_height and symbol triangle_char.

(1) The given program outputs a fixed-height triangle using a * character. Modify the given program to output a right triangle that instead uses the user-specified triangle_char character.

(2) Modify the program to use a loop to output a right triangle of height triangle_height. The first line will have one user-specified character, such as % or *. Each subsequent line will have one additional user-specified character until the number in the triangle's base reaches triangle_height. Output a space after each user-specified character, including a line's last user-specified character.

I'm having trouble figuring out how to create a space between my characters. Example input is % and 5. My code is:

triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')

for i in range (triangle_height):
    print((triangle_char) * (i + 1))

my output is:

%
%%
%%%
%%%%
%%%%%

while expected output is:

% 
% % 
% % % 
% % % % 
% % % % % 


Solution 1:[1]

You need to use join(). This would work:

for i in range(triangle_height):
    print(' '.join(triangle_char * (i + 1)))

It is adding spaces between every character because strings are iterable.

This may be optimized a bit by having a list of the characters and appending 1 character in each iteration, rather than constructing triangle_char * (i+1) every time.

Solution 2:[2]

This should fix the white space errors:

for i in range(triangle_height):
    print(' '.join(triangle_char * (i + 1)) + ' ')

Solution 3:[3]

for i in range(triangle_height+1):
     print(f'{triangle_char} '*i)

Solution 4:[4]

I see the popular way so far is using join, but another way while trying to stay true to the original idea is you simply can add a white space after each character. See below:

triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')

for i in range(triangle_height):
    print((triangle_char + ' ') * (i + 1))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 shriakhilc
Solution 2 CKE
Solution 3 richardec
Solution 4 ObscuredData