Python Program to Print Diamond Pattern

Introduction

A diamond pattern consists of a symmetric arrangement of stars (*) where the stars form a diamond shape. The pattern consists of two parts: an upper triangle and a lower inverted triangle. This exercise helps in understanding how to use loops and control output in a visually appealing way.

Problem Statement

Create a Python program that:

  • Accepts the number of rows for the diamond pattern (the upper part).
  • Prints a diamond pattern using stars (*).

Example:

  • Input: rows = 5
  • Output:
        *
       ***
      *****
     *******
    *********
     *******
      *****
       ***
        *
    

Solution Steps

  1. Input the Number of Rows: The user defines the number of rows for the upper part of the diamond.
  2. Use Nested Loops: The outer loops handle the rows, and the inner loops handle printing the stars and spaces for both the upper and lower parts of the diamond.
  3. Display the Diamond Pattern: Print stars in increasing order for the upper part and decreasing order for the lower part, using spaces for alignment.

Python Program

# Step 1: Input the number of rows for the upper part of the diamond
rows = int(input("Enter the number of rows: "))

# Step 2: Print the upper part of the diamond
for i in range(1, rows + 1):
    # Print spaces for alignment
    print(" " * (rows - i), end="")
    # Print stars for the current row
    print("*" * (2 * i - 1))

# Step 3: Print the lower part of the diamond
for i in range(rows - 1, 0, -1):
    # Print spaces for alignment
    print(" " * (rows - i), end="")
    # Print stars for the current row
    print("*" * (2 * i - 1))

Explanation

Step 1: Input the Number of Rows

  • The program starts by asking the user for the number of rows. This number determines the height of the upper triangle of the diamond.

Step 2: Print the Upper Part of the Diamond

  • The first loop handles the upper triangle.
    • The first inner part prints spaces to align the stars.
    • The second part prints stars (*) in increasing order using the formula 2 * i - 1 to ensure the correct number of stars for each row.

Step 3: Print the Lower Part of the Diamond

  • The second loop handles the inverted triangle (lower part).
    • The first part prints spaces, and the second part prints stars in decreasing order.

Output Example

For rows = 5, the output will be:

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

For rows = 4, the output will be:

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

Conclusion

This Python program prints a diamond pattern using stars (*). The program uses nested loops to print the upper and lower parts of the diamond, with spaces for alignment. This exercise is helpful for practicing loop control and output formatting in Python.

Comments