Python Program to Print Heart Pattern
for loops and if conditions to print stars in the shape of a heart, for example: for row in range(6): for col in range(7): print('*' if (row == 0 and col % 3 != 0) or (row == 1 and col % 3 == 0) or (row - col == 2) or (row + col == 8) else ' ', end=''); print().Examples
How to Think About It
Algorithm
Code
for row in range(6): for col in range(7): if (row == 0 and col % 3 != 0) or (row == 1 and col % 3 == 0) or (row - col == 2) or (row + col == 8): print('*', end='') else: print(' ', end='') print()
Dry Run
Let's trace the heart pattern printing for the first two rows.
Row 0, Columns 0 to 6
Positions 1, 2, 4, 5 print '*', others print ' '
Row 1, Columns 0 to 6
Positions 0, 3, 6 print '*', others print ' '
| Row | Col | Condition Met | |
|---|---|---|---|
| 0 | 0 | False | ' ' |
| 0 | 1 | True | '*' |
| 0 | 2 | True | '*' |
| 0 | 3 | False | ' ' |
| 0 | 4 | True | '*' |
| 0 | 5 | True | '*' |
| 0 | 6 | False | ' ' |
| 1 | 0 | True | '*' |
| 1 | 1 | False | ' ' |
| 1 | 2 | False | ' ' |
| 1 | 3 | True | '*' |
| 1 | 4 | False | ' ' |
| 1 | 5 | False | ' ' |
| 1 | 6 | True | '*' |
Why This Works
Step 1: Upper arcs of the heart
The first two rows create the two rounded tops of the heart using conditions on row and column positions.
Step 2: Lower triangle shape
The conditions row - col == 2 and row + col == 8 create the slanting sides of the heart's bottom.
Step 3: Printing stars and spaces
Stars are printed where conditions are true to form the heart shape; spaces fill the rest to keep the shape clear.
Alternative Approaches
heart = [ ' ** ** ', ' * * * ', '* *', '* *', ' * * ', ' * * ', ' ** ' ] for line in heart: print(line)
for y in range(15, -15, -1): for x in range(-30, 30): if (x*0.04)**2 + (y*0.1)**2 - 1 <= 0 and (x*0.04)**2 + (y*0.1)**2 - 1 >= -0.3: print('*', end='') else: print(' ', end='') print()
Complexity: O(n*m) time, O(1) space
Time Complexity
The program uses nested loops over rows (n) and columns (m), so time grows with the size of the pattern.
Space Complexity
Only a few variables are used; printing is done directly, so space is constant.
Which Approach is Fastest?
Using predefined strings is fastest but less flexible; loop-based drawing is more flexible but slightly slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop with conditions | O(n*m) | O(1) | Flexible patterns |
| Predefined strings | O(n) | O(n*m) | Simple fixed patterns |
| Mathematical equation | O(n*m) | O(1) | Smooth shapes, complex |