Python Program to Print a Diamond Pattern
Beginner · Patterns
A diamond pattern is a pyramid with an upside-down pyramid underneath it. With 5 rows in the top half, the rows have 1, 3, 5, 7 and 9 stars, then 7, 5, 3 and 1 again. The bottom half skips the widest row so it is not printed twice.
Program
*
***
*****
*******
*********
*******
*****
***
*How it works
- Both halves use the same rule: row
ihasrows - ispaces followed by2 * i - 1stars. - The first loop counts
iup from 1 torows, which draws a pyramid ending with the widest row of 9 stars. - The second loop counts
idown fromrows - 1to 1, which draws the same rows again in reverse. - Starting the second loop at
rows - 1instead ofrowsstops the widest row from appearing twice. " " * nand"*" * nrepeat a character n times, so each row is built without an inner loop.
Other ways to write it
One loop using abs()
*
***
*****
*******
*********
*******
*****
***
*abs(k) is the distance from the middle row, so a single loop from -4 to 4 prints fewer spaces and more stars as it nears the middle, and the reverse after it.
Hollow diamond
*
* *
* *
* *
* *
* *
* *
* *
*Only the first and last positions of each row get a star, with width - 2 spaces between them, so just the outline of the diamond is drawn.
Try it yourself
Change rows to 7 and replace the stars with the first letter of your name.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises