Czar Luc
Czar Luc

Reputation: 95

python pyramid pattern print using for loop

how do you manipulate the for loop to display an output just like

5
54
543
5432
54321

I tried coding like

n=6
for i in range(0,n):
    for j in range (n,0):
        print(j,end="")
print(i)

but it would print this

0
1
2
3
4
5

Shouldn't it print first the 5 in loop j first

Upvotes: 1

Views: 1937

Answers (2)

user94559
user94559

Reputation: 60143

A bunch of ways to solve this... here's one:

n = 5

for i in range(0, n):
    # Think of this range as "how many numbers to print on this line"
    for j in range(i + 1):
        # First number should be n, second n - 1, etc.
        print(n - j, end="")
    print() # newline before next i

(Note that I changed n to 5.)

Upvotes: 2

Błotosmętek
Błotosmętek

Reputation: 12927

Almost good, but to go down from n, range requires the third parameter - step - to be -1:

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

Upvotes: 3

Related Questions