Python Program to Print P Star Pattern

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

The below alphabet P star pattern example accepts the user-entered rows, and the nested for loop iterates the rows. The elif condition is to print stars at the first column and first and middle rows to get the Alphabetical P pattern of stars and skip others.

rows = int(input("Enter Alphabet P of Stars Rows = "))
print("====The Alphabet P Star Pattern====")

for i in range(rows):
    for j in range(rows):
        if j == 0 or (i == 0 or i == rows // 2) and j < rows - 1:
            print("*", end="")
        elif i != 0 and i < rows // 2 and j == rows - 1:
            print("*", end="")
        else:
            print(end=" ")
    print()
Python Program to Print Alphabetical P Star Pattern

Python program to print the Alphabet P Star pattern using while loop

Instead of a For loop, this program uses the while loop to iterate the Alphabet P pattern rows and prints the stars at the required positions. For more Star Pattern programs >> Click Here.

rows = int(input("Enter Alphabet P of Stars Rows = "))

i = 0
while i < rows:
    j = 0
    while j < rows:
        if j == 0 or (i == 0 or i == rows // 2) and j < rows - 1:
            print("*", end="")
        elif i != 0 and i < rows // 2 and j == rows - 1:
            print("*", end="")
        else:
            print(end=" ")
        j = j + 1
    print()
    i = i + 1
Enter Alphabet P of Stars Rows = 12
*********** 
*          *
*          *
*          *
*          *
*          *
*********** 
*           
*           
*           
*           
*  

In this Python example, we created a pPattern function that accepts the rows and the symbol or character to print the Alphabet P pattern of the given symbol.

def pPattern(rows, ch):
    for i in range(rows):
        for j in range(rows):
            if j == 0 or (i == 0 or i == rows // 2) and j < rows - 1:
                print('%c' %ch, end='')
            elif i != 0 and i < rows // 2 and j == rows - 1:
                print('%c' %ch, end='')
            else:
                print(end=" ")
        print()


row = int(input("Enter Alphabet P of Stars Rows = "))
sy = input("Symbol for P Star Pattern = ")
pPattern(row, sy)
Enter Alphabet P of Stars Rows = 14
Symbol for P Star Pattern = $
$$$$$$$$$$$$$ 
$            $
$            $
$            $
$            $
$            $
$            $
$$$$$$$$$$$$$ 
$             
$             
$             
$             
$             
$