2
votes

Currently, I have a code that outputs an asterisk triangle like this:

* 
* * 
* * * 
* * * * 
* * * * * 

Here is the code for it:

num = int(input("Enter the number of rows: "))
for i in range(1,num+1):
    for j in range(1,i+1):
        print("*",end=' ')
    print()

Now, how can I use/modify the same code above to make the triangle look like this:

        *
      * *
    * * *
  * * * *
* * * * * 

Any suggestions?

4
This code does not produce the triangle here. I took the liberty to correct it - rafaelc
you are....correct. o__o let me fix that quickly. I was playing around with it. - LotusAlice
@RafaelC Thank you, that was a very negligent mistake on my part. Sorry about that. - LotusAlice

4 Answers

5
votes

Using the string method str.rjust:

>>> num = int(input("Enter the number of rows: "))
>>> for i in range(1, num + 1):
...     print(" ".join("*" * i).rjust(num * 2))
Enter the number of rows: 5
         *
       * *
     * * *
   * * * *
 * * * * *
0
votes

Here is a function that can do it either way:

def tristar(n,rev=False):
    for i in range(1,n+1):
        if rev:
            s = ' ' * (n-i) + '*' * i
            print(s)
        else:
            s = '*' * i
            print(s)
0
votes

In case you are not allowed to use rjust:

num = int(input("Enter the number of rows: "))
for i in range(1, num + 1):
    for j in range(num, 0, -1):
        if j <= i:
            print('*', end=' ')
        else:
            print(' ', end=' ')
    print()

or alternatively:

num = int(input("Enter the number of rows: "))
for i in range(num, 0, -1):
    for j in range(1, num + 1):
        if i > j:
            print(' ', end=' ')
        else:
            print('*', end=' ')
    print()
-1
votes

The following code will print a reversed triangle:

for i in range(1,6):
    print("{:>5s}".format("*"*i))

Output:

    *
   **
  ***
 ****
*****