Simple Diamond Pattern in Python
Last Updated :
29 May, 2021
Improve
Given an integer n, the task is to write a python program to print diamond using loops and mathematical formulations. The minimum value of n should be greater than 4.
Examples :
For size = 5 * * * * * * * * * * * * For size = 8 * * * * * * * * * * * * * * * * * * * * * * * * * * For size = 11 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Approach :
The following steps are used :
- Form the worksheet of (size/2+2) x size using two loops.
- Apply the if-else conditions for printing stars.
- Apply else condition for rest spaces.
Below is the implementation of the above approach :
Example 1:
# define the size (no. of columns)
# must be odd to draw proper diamond shape
size = 8
# initialize the spaces
spaces = size
# loops for iterations to create worksheet
for i in range(size//2+2):
for j in range(size):
# condition to left space
# condition to right space
# condition for making diamond
# else print *
if j < i-1:
print(' ', end=" ")
elif j > spaces:
print(' ', end=" ")
elif (i == 0 and j == 0) | (i == 0 and j == size-1):
print(' ', end=" ")
else:
print('*', end=" ")
# increase space area by decreasing spaces
spaces -= 1
# for line change
print()
Output :
* * * * * * * * * * * * * * * * * * * * * * * * * *
Example 2:
# define the size (no. of columns)
# must be odd to draw proper diamond shape
size = 11
# initialize the spaces
spaces = size
# loops for iterations to create worksheet
for i in range(size//2+2):
for j in range(size):
# condition to left space
# condition to right space
# condition for making diamond
# else print ^
if j < i-1:
print(' ', end=" ")
elif j > spaces:
print(' ', end=" ")
elif (i == 0 and j == 0) | (i == 0 and j == size-1):
print(' ', end=" ")
else:
print('*', end=" ")
# increase space area by decreasing spaces
spaces -= 1
# for line change
print()
Output :
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *