Home > front end >  I got single line as output, but i have to get given number of rows
I got single line as output, but i have to get given number of rows

Time:09-26

code:

row = int(input('enter a number:'))

while row != 0:
    for i in range(row, 0, -1):
        for j in range(i):
            print(i, end=" ")
        row = row - 1

actual output:

enter a number:4
4 4 4 4 3 3 3 2 2 1

expected output:

enter a number:4
4 4 4 4 3 3 3 2 2 1
4 4 4 4 3 3 3 2 2 1
4 4 4 4 3 3 3 2 2 1
4 4 4 4 3 3 3 2 2 1

CodePudding user response:

you need tmp and for-loop at first, (I don't change or improve your code)

Try this:

row = int(input('enter a number:'))
tmp = row
for _ in range(tmp):
    row = tmp
    while row != 0:
        for i in range(row, 0, -1):
            for j in range(i):
                print(i, end=" ")
            row = row - 1
    print()

Output:

enter a number:5
5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 
5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 
5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 
5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 
5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 

For improving you can try this:

row = int(input('enter a number:'))
for _ in range(row):
    print(*[f'{i} '*i for i in range(row,0,-1)])
  • Related