Python 3 Beginner – Iterating Triangle

Question:

I am going through a past test and the output of the code is this:

Enter the height:
5
     5
    44
   333
  2222
 11111

I have to write down the code – so far I know how to make a normal triangle with:

 for i in range(5):
 print('*'*i)

 *
 **
 ***
 ****

My main question is how do I get the body if the triangle to iterate over the numbers?

So what would the code of the first triangle be?
Help would be appreciated:)

Asked By: user3490976

||

Answers:

You can use str:

for i in range(5):
 print(str(i)*i)
Answered By: venpa

The code for this is virtually the same, you just need to change the number of times you print each character, and change the * that you are printing to a number.

for i in range(5):
    print(str(5-i) * (i+1))

This generates:

5    
44   
333  
2222 
11111

To make it right aligned, like in your example, just use string multiplication on a space character.

for i in range(5):
    print(' ' * (4-i) + str(5-i) * (i+1))

This will get you:

    5
   44
  333
 2222
11111
Answered By: Lily Mara

Formatted string & spacing with an external array and a negated variable.

def height(num):
  rangenum=range(num+1)
  for i in rangenum:
    print(("%"+str(num)+"s")%(i*str(rangenum[-i])))

print("%(spacing as a number)s"%(a string))

returns

(spacing as a number)-(a string)

example:

print("%10s"%"this")

returns:

"      this"

side note:

%-(a number)s

is right justified.

(though python tries to cut down the millions of ways to do the same thing, there still are thousands)

https://docs.python.org/2/tutorial/inputoutput.html

Answered By: gabeio

Some of the other answers have been essentially correct, but this one right justifies your triangle like the original output.

def print_triangle(rows):
    for i in range(rows + 1):
        print((str(rows + 1-i)*i).rjust(rows))
Answered By: Nicholas Flees
height = 5
for i in range(height, 0, -1):
    empty_chars = ' ' * (i - 1)
    filler_chars = str(i) * (height - i + 1)
    print('{}{}'.format(empty_chars, filler_chars))
Answered By: s16h

what if we want to produce
1 1 1 1 1
2 2 2 2
3 3 3
4 4
5
but using nested while loop.
any advice would be appreciated.

Answered By: Yuchao Huang
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.