Python Program to Print Alphabet H pattern of stars

This article shows how to write a Python program to print the Alphabet H pattern of stars using the for loop, while loop, and functions with an example.

The below star H pattern example accepts the user-entered rows, and the nested for loop iterates the rows. The If else condition is to print stars at a few positions and skip others to get the Alphabet H pattern of stars.

rows = int(input("Enter H Star Pattern Rows = "))

print("====The Alphabet H Star Pattern====")

for i in range(rows):
    print('*', end='')
    for j in range(rows):
        if i == rows // 2 or j == rows - 1:
            print('*', end='')
        else:
            print(end=' ')
    print()
Python program to print the Alphabet H pattern of stars using for loop

Python program to print the Alphabet H pattern of stars using while loop

Instead of a For loop, this program uses the while loop to iterate the H pattern rows and prints the stars at each position. Here, we used an extra if statement to add an extra row for the even numbers to get the H in the middle. For more Star Pattern programs >> Click Here.

rows = int(input("Enter H Star Pattern Rows = "))

if rows % 2 == 0:
    rows = rows + 1

i = 0
while i < rows:
    print('*', end='')
    j = 0
    while j < rows:
        if i == rows // 2 or j == rows - 1:
            print('*', end='')
        else:
            print(end=' ')
        j = j + 1
    print()
    i = i + 1
Enter H Star Pattern Rows = 8

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

In this example, we created an HPattern function that accepts the rows and the symbol or character to print the Alphabet H pattern of the given symbol.

def HPattern(rows, ch):
    for i in range(rows):
        print('%c' %ch, end='')
        for j in range(rows):
            if i == rows // 2 or j == rows - 1:
                print('%c' %ch, end='')
            else:
                print(end=' ')
        print()


rows = int(input("Enter H Star Pattern Rows = "))

ch = input("Symbol for H Pattern = ")

HPattern(rows, ch)
Enter H Star Pattern Rows = 9
Symbol for H Pattern = $

$        $
$        $
$        $
$        $
$$$$$$$$$$
$        $
$        $
$        $
$        $