You can look at the exercise from a conceptual manner too.

The first thing that can strike you is that you are being asked to draw spaces and asterisks. So in fact you are being asked to draw a rectangle. And you even already have one of the sizes; the number of lines gives you the height. You can then expand on this concept to devise the formula that will enable you to know the width. For that, you now need to look at the triangle itself.

You need to find a pattern you can use as a formula. For that, why not start with the last line and see what properties we can find as we move up the triangle? We could also start from the top. However, patterns are usually less challenging when working with bigger numbers and they can also break when we work with the number 1 or 0. e.q. More often than not we need to create an exception when the significant element of the formula (the element that grows or shrinks) is 1 or 0. So it's easier to start from the bottom where the bigger numbers are and then see if that exception needs to be created.

So... the last line in your example is line 5 and it has 9 asterisks. The height of your rectangle is 5 and the width is 9. Next...

Code:

(line 5, height = 5, width = 9)
line 4, height = 4, width = 7
line 3, height = 3, width = 5
line 2, height = 2, width = 3
line 1, height = 1, width = 1

What can we see as a pattern? Before you read further on, take some time to try and see it yourself...

Well, each line width is equal to *line_height * 2 - 1*. And it even works with 1! Although it will break with 0. You cannot have -1 asterisks.

So... with that formula you can now easily create your triangle with just one for loop. The best way is to first store the width in an integer before you enter the loop. Each line will be equal to:

*(overall_width - line_width) / 2* in spaces concatenated to,

*line_width* in asterisks concatenated to,

*(overall_width - line_width) / 2* in spaces.

The only other care you will need to have is to either not accept 0 as an input for the height of the triangle or accept it, but output an empty string.