Open In App

Python program to display half diamond pattern of numbers with star border

Given a number n, the task is to write a Python program to print a half-diamond pattern of numbers with a star border.

Examples:



Input: n = 5
Output:

*
*1*
*121*
*12321*
*1234321*
*123454321*
*1234321*
*12321*
*121*
*1*
*


Input: n = 3
Output:

*
*1*
*121*
*12321*
*121*
*1*
*

Approach:

Below is the implementation of the above pattern:






# function to display the pattern up to n
def display(n): 
   
    print("*")
     
    for i in range(1, n+1):
        print("*", end="")
         
        # for loop to display number up to i
        for j in range(1, i+1): 
            print(j, end="")
 
        # for loop to display number in reverse direction   
        for j in range(i-1, 0, -1): 
            print(j, end="")
 
        print("*", end="")
        print()
 
    # for loop to display i in reverse direction
    for i in range(n-1, 0, -1):
        print("*", end="")
        for j in range(1, i+1):
            print(j, end="")
 
        for j in range(i-1, 0, -1):
            print(j, end="")
 
        print("*", end="")
        print()
 
    print("*")
 
 
# driver code
n = 5
print('\nFor n =', n)
display(n)
 
n = 3
print('\nFor n =', n)
display(n)

Output
For n = 5
*
*1*
*121*
*12321*
*1234321*
*123454321*
*1234321*
*12321*
*121*
*1*
*

For n = 3
*
*1*
*121*
*12321*
*121*
*1*
*

Article Tags :