Given an even integer n, the task is to print a heart-shaped pattern using stars (*) and simple loop logic in Python. For Example:
For n = 8, the output is:
* * * *
* * *
* *
* G F G *
* *
* *
* *
*
For n = 14, a larger heart is printed with the same structure.
Code Implementation
This method prints the heart by splitting it into two parts:
- The upper part creates the two rounded lobes.
- The lower part creates the pointed bottom and prints GFG at the center.
Stars and characters are printed by checking the row and column positions using simple mathematical conditions.
n = 8
m = n+1
# loops for upper part
for i in range(n//2-1):
for j in range(m):
if i == n//2-2 and (j == 0 or j == m-1):
print("*", end=" ")
elif j <= m//2 and ((i+j == n//2-3 and j <= m//4) \
or (j-i == m//2-n//2+3 and j > m//4)):
print("*", end=" ")
elif j > m//2 and ((i+j == n//2-3+m//2 and j < 3*m//4) \
or (j-i == m//2-n//2+3+m//2 and j >= 3*m//4)):
print("*", end=" ")
else:
print(" ", end=" ")
print()
# loops for lower part
for i in range(n//2-1, n):
for j in range(m):
if (i-j == n//2-1) or (i+j == n-1+m//2):
print('*', end=" ")
elif i == n//2-1:
if j == m//2-1 or j == m//2+1:
print('G', end=" ")
elif j == m//2:
print('F', end=" ")
else:
print(' ', end=" ")
else:
print(' ', end=" ")
print()
Output
* * * *
* * *
* *
* G F G *
* *
* *
* *
*
Explanation:
- n sets the size of the heart and m = n + 1 maintains symmetry.
- The first loop (for i in range(n//2 - 1)) prints the upper curved part using position checks like i + j and j - i.
- The second loop prints the lower pointed part using diagonals formed by i - j and i + j.
- When i == n//2 - 1, the text G F G is printed at the center using m//2.
- print(..., end=" ") keeps proper spacing and alignment.