Python Program to Print a Heart Pattern
Intermediate · Patterns
A heart pattern draws a heart out of stars: two rounded humps on top and a point at the bottom. This program builds it from shapes you already know, two small pyramids side by side for the humps and an upside-down pyramid for the point.
Program
*** ***
***** *****
******* *******
*************
***********
*********
*******
*****
***
*How it works
- The top of the heart is two humps, and each hump is a small pyramid whose row
ihas2 * i + 3stars: 3, then 5, then 7. edgeindents the left hump one space less on each row, andgap, the space between the humps, shrinks as they grow until a single space separates them.- The bottom is an inverted pyramid whose first row has
4 * size - 3stars (13 whensizeis 4), just narrower than the top, so the sides curve inwards. - Each bottom row is indented one more space and loses 2 stars, ending in a single star at the point.
- Every part is worked out from
size, so changing that one number draws a smaller or bigger heart.
Other ways to write it
Hollow heart from a grid
* * * *
* * *
* *
* *
* *
*The heart is drawn on a 6 by 7 grid with a rule for each part: the two humps on the first two rows, and two diagonal lines, row - col == 2 and row + col == 8, that meet at the point.
Using the heart curve equation
************ ************
*********************************
***********************************
***********************************
*************************************
*************************************
***********************************
***********************************
*********************************
*********************************
*****************************
***************************
***********************
*******************
***************
*********
*****
*Mathematicians have a formula whose solutions form a heart, so the program checks every point of a grid and prints a star wherever the formula is true, which gives the heart smooth curves.
Try it yourself
Change size to 6 for a bigger heart, then replace the stars with @.
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