Diamond pattern program in Python
Written by
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:
- Accept input for the number of rows needed to create a diamond pattern.
- Use a for loop with the range of the number of rows to iterate through each row.
- 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.
- Print a space for each iteration of the inner loop.
- After the inner loop, use another for loop with a range of 1 to the number of asterisks needed for the current row.
- Print an asterisk for each iteration of the inner loop.
- 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.
- 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:
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*