Python Program for Heart Shape Pattern

1. Introduction

Creating a heart shape pattern in programming is a delightful challenge that combines loops, conditionals, and a bit of creativity. This Python program demonstrates how to print a heart shape using asterisks (*), perfect for beginners looking to practice and enhance their understanding of Python's control structures.

2. Program Steps

1. Determine the dimensions of the heart shape.

2. Use nested loops to iterate over each point in the pattern's grid.

3. Apply conditional logic within the loops to decide whether to print an asterisk (*) or a space, based on the coordinates to form a heart shape.

3. Code Program

# Function to print heart shape
def print_heart_shape():
    for row in range(6):
        for col in range(7):
            # Conditions to print the stars forming a heart shape
            if (row == 0 and col % 3 != 0) or (row == 1 and col % 3 == 0) or (row - col == 2) or (row + col == 8):
                print("*", end=" ")
                print(" ", end=" ")
        print()  # Move to the next line after each row

# Main program
if __name__ == "__main__":


 * *   * *
*   * *   *
*     *    *
 *         *
  *       *
   * * *


1. The program defines a function print_heart_shape that does not take any parameters. This function is responsible for printing the heart shape pattern.

2. The function uses nested loops to iterate over a grid of rows and columns. The outer loop iterates through rows, while the inner loop iterates through columns.

3. Inside the inner loop, conditional statements determine whether to print an asterisk (*) or a space. The conditions are based on the row and column indices and are designed to outline the heart shape. Specifically, the conditions are:

- The top rows form the upper lobes of the heart, using modulo arithmetic to skip certain columns.

- The middle part of the heart is formed by diagonal lines (row - col == 2 and row + col == 8).

4. After each column in a row is processed, a newline character is printed (print()), which moves the cursor to the next line, ensuring the pattern is printed correctly.

5. The if __name__ == "__main__">: block checks if the program is being run directly (not imported as a module), and if so, it calls the print_heart_shape function to print the pattern.

6. This program showcases the use of simple arithmetic and conditional logic to create complex and visually appealing patterns in Python.