Printing Simple Pattern in Python

Printing Simple Pattern in Python

Problem Description:

I would like to print the following pattern in Python

input: 5

output:

    5
   456
  34567
 2345678
123456789

I have used the following code but it is not showing the above pattern. Anyone help me on this topic, please?

CODE:

rows = int(input("Enter number of rows: "))

k = 0
count=0
count1=0

for i in range(1, rows+1):
    for space in range(1, (rows-i)+1):
        print("  ", end="")
        count+=1

    while k!=((2*i)-1):
        if count<=rows-1:
            print(i+k, end=" ")
            count+=1
        else:
            count1+=1
            print(i+k-(2*count1), end=" ")
        k += 1

    count1 = count = k = 0
    print()

OUTPUT:

        1
      2 3 2
    3 4 5 4 3
  4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5

Solution – 1

If I understand your question correctly, you just want a pattern starting from n and going to 1 in decreasing order left side, and starting from n and going to 2n-1 in increasing order right side

  def pattern(n):
        for i in range(n,0,-1):
            for j in range(1,i):
                print(" ",end="")
            for k in range(i,2*n-i+1):
                print(k,end="")
            print()

pattern(5)

    5
   456
  34567
 2345678
123456789
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject