Python Program for Hourglass Pattern

1. Introduction

The hourglass pattern is an interesting figure in pattern programming, where asterisks (*) are used to create a shape resembling an hourglass. This pattern involves printing a series of asterisks that first decrease in number with each row and then increase, creating a symmetric figure. It's a great exercise for beginners to learn about loops and conditional statements in Python.

2. Program Steps

1. Define the height of the hourglass, which will control the number of rows in the pattern.

2. Use nested loops to print the upper half of the hourglass, where the number of asterisks decreases with each row.

3. Use nested loops to print the lower half of the hourglass, where the number of asterisks increases with each row.

3. Code Program

# User input for the height of the hourglass
height = int(input("Enter the height of the hourglass: "))

# Ensure the height is an odd number
if height % 2 == 0:
    height += 1

# Print the upper half of the hourglass
for i in range(height // 2, 0, -1):
    print(' ' * ((height // 2) - i) + '*' * (2 * i - 1))

# Print the center of the hourglass
print(' ' * (height // 2) + '*')

# Print the lower half of the hourglass
for i in range(2, height // 2 + 2):
    print(' ' * ((height // 2) - i + 1) + '*' * (2 * i - 1))

Output:

Enter the height of the hourglass: 7
*******
 *****
  ***
   *
  ***
 *****
*******

Explanation:

1. The program begins by asking the user to input the height of the hourglass. This value determines the total number of rows in the pattern.

2. If the user enters an even number, the program adjusts the height to the next odd number to maintain symmetry in the hourglass pattern.

3. The program then prints the upper half of the hourglass using a loop that starts from the middle of the hourglass and decreases to 1. The number of asterisks printed on each row decreases as the loop progresses, and leading spaces are added to keep the asterisks centered.

4. The center of the hourglass is printed as a single asterisk, centered by adding spaces equal to half the height of the hourglass.

5. The lower half of the hourglass is printed using a loop that starts from 2 and increases to the middle of the hourglass. The number of asterisks printed on each row increases as the loop progresses, mirroring the upper half of the hourglass.

6. This method of using nested loops and adjusting the number of spaces and asterisks printed in each row creates a symmetric hourglass pattern, demonstrating the flexibility and power of Python for generating complex patterns with simple code.


Comments