pythonnumberstriangle

Python How to make a number triangle


So I've recently started learning python and my friend gave me a changllege. How to make a number triangle. So basically, I need to make python let me input a number, for example 5. After I do that, I want python to print

54321
4321
321
21
1

But because I am new to python, I don't know how to do it. So far, I've got this:

x = int(input('Enter a Number: '))

for i in range(x,0,-1):
  print(i,end='')
  if i != 0:
    continue
  else:
    break

And the output is:

Enter a Number: 5
54321

Any ideas how to make it print 54321 4321 321 21 1 ? Thanks for any advice


Solution

  • Here is a sample code for you.

    Short version (suggest learning about list comprehension and join functions):

    x = int(input('Enter a Number: '))
    for i in range(x, 0, -1):
        print(''.join([str(j) for j in range(i, 0, -1)]))
    

    Longer version which is easier to understand:

    for i in range(x, 0, -1):
        s = ''
        for j in range(i, 0, -1):
            s += str(j)
        print(s)
    

    Output:

    54321
    4321
    321
    21
    1