Diamond pattern program in Python

Written by

Himani Kohli

Python diamond pattern program(using for loop)

In this example, we will learn to create a diamond shape using n numbers in python. Here, we will develop the shape of a diamond with 2n rows.

Our main motive is to design a diamond shape pattern using star symbols and print across the lines.

Algorithm:

  1. Accept input for the number of rows needed to create a diamond pattern.
  2. Use a for loop with the range of the number of rows to iterate through each row.
  3. For the first half of the diamond, use a nested for loop with a range of 1 to the number of spaces needed for the current row.
  4. Print a space for each iteration of the inner loop.
  5. After the inner loop, use another for loop with a range of 1 to the number of asterisks needed for the current row.
  6. Print an asterisk for each iteration of the inner loop.
  7. For the second half of the diamond, use the same structure as the first half, but with reversed ranges and different variables for the number of spaces and asterisks needed.
  8. After the outer loop, the diamond pattern should be displayed on the screen.

Code:

n=int(input("enter the number of rows"))

for i in range(n):

    for j in range(1,int((n/2))-i+3):

        print(sep=" ",end=" ")

    for k in range(1,i+2):

        print("*", end=" ")

        

    print()

for i in range(n):

    for j in range(1,5-(int((n/2))-i+3)+2):

        print(sep=" ",end=" ")

    for k in range(1,5-i):

        print("*", end=" ")

    print()

Output:


         * 
        *** 
       ***** 
      ******* 
     ********* 
    *********** 
   ************* 
  *************** 
 ***************** 
*******************
 ***************** 
  *************** 
   ************* 
    *********** 
     ********* 
      ******* 
       ***** 
        *** 
         *
Diamond pattern program in Python