Aurora S.
Aurora S.

Reputation: 23

How do I draw a reverse triangle using characters and nested while loops in Python code?

I have already drawn a right-side-up right triangle already that looks like this:

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

with code:

row = 1
while row <= size:
    col = 1
    while col <= row:
        print chr, 
        col = col + 1

    print '' 

    row = row + 1
print ''

But I need to draw a triangle that looks like this:

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

and I am not entirely sure how to go about it. I know it requires at least 2 nested loops utilizing printing spaces as well as the character. It is required that only while loops are used.

I would appreciate it if someone could shed light on how to write this for me.

Upvotes: 1

Views: 7175

Answers (4)

Sar ibra
Sar ibra

Reputation: 5

    size = 10
    def draw(n):
        if n<=size:
            draw(n+1)
            for i in range(n):
                print("#", end="")
            print(end= "\n")


    draw(0)

Upvotes: 0

Use shortest

num = int(raw_input('Enter number :'))
for a in reversed(range(num+1)):
    print ' '*(num-a)+'*'*(a)

Enter number :7
*******
 ******
  *****
   ****
    ***
     **
      *

Upvotes: -1

Raiyan
Raiyan

Reputation: 1687

Edited to make rotate triangle, also came up with a better way of doing it

chr = "*"
size = 5
row = 1
while row <= size:
    col = size - row + 1
    while col <= size:
        print ' ', 
        col = col + 1
    col = 0
    while col <= size-row:
        print chr, 
        col = col + 1
    row = row + 1
    print ''
print ''

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

Using str.join:

def solve(width):
    for i in xrange(width, 0, -1):
        print ' '.join([' ']*(width-i) + ['*']*i)
...         
>>> solve(5)
* * * * *
  * * * *
    * * *
      * *
        *
>>> solve(7)
* * * * * * *
  * * * * * *
    * * * * *
      * * * *
        * * *
          * *
            *

Upvotes: 3

Related Questions