Printing diamond pattern in Python
This tutorial will help you learn about how to make or print a diamond pattern in Python. Printing of pattern is an easy a funloving part of coding be it in any language. We will learn about printing the diamond pattern in python.
You may learn these similar tutorials:
By the time you will be done reading this post, you will have enough knowledge to code a diamond shape in python.
Analyzing the diamond pattern
The diamond pattern is nothing but two triangles merged with their bases in contact with each other.
CODING CONCEPT (IN PYTHON 3)
We will follow the following steps to make the diamond pattern :
- printing the upper triangle
- printing the lower triangle
When done both we will have a diamond shape ready for us.
Let us begin!
We will analyze the coding concept using a 2D matrix. First, we will take a user input (say rows) of the number of rows. The number of columns will be (2 x No. of rows -1) as there will a definite pattern while printing triangle.
Example: Row 1 will have 1 star, row 2 will have 3 stars and similarly row 3 will have 5 stars. Therefore, n rows will have (2n-1) columns.
Now, when the matrix is made we will begin with i=0, i<rows and j=0, j<columns. This marks (0,0) in the matrix. We will print ‘*’ at the place where the condition [(columns//2)-i <= j <= (columns//2) +i] is satisfied and blank spaces at the rest of the spots.
Print(” “) changes the line in python, it is specific to python as by default it changes the line after every command.
print('first line') print('\n') print('second line')
OUTPUT: first line second line
- This output has 2 line changes. One is due to ‘\n’ and the other one is due to the execution of the first print command.
We will increment ‘i’ and then again the condition will be checked. This will be done until the upper triangle is made.
Again, we will set ‘i’ and ‘j’ to 0(zero) to begin with printing the upside-down triangle. This time the condition that will be checked will be
(i <= j <= columns-1 -i ) and if this is satisfied we will print ‘*’ else blank spaces will be printed.Print(” “) changes the line in python, it is specific to python as by default it changes line at every command. This will be done until the lower triangle is made.
This process in end will result in the making of diamond shape.
Program to print diamond pattern in Python
rows = int(input("Enter The Number Of Rows: ")) columns = 2*rows -1 i = 0 while i < rows: j = 0 while j < columns : if( (columns//2)-i <= j <= (columns//2) +i): print("*",end = "") else: print(" ",end = "") j+=1 print(" ") i+=1 i = 0 while i < rows: j = 0 while j < columns : if( i <= j <= columns-1 -i): print("*",end = "") else: print(" ",end = "") j+=1 print(" ") i+=1
INPUT: Enter The Number Of Rows: 5 OUTPUT:
* *** ***** ******* ********* ******* ***** *** *