This article shows how to write a Python program to print the Alphabet U star pattern using the for loop, while loop, and functions with an example.
The below alphabet U 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 and last columns, and last row to get the Alphabetical U pattern of stars and skip others.
rows = int(input("Enter Alphabet U of Stars Rows = ")) print("====The Alphabet U Star Pattern====") for i in range(rows): for j in range(rows): if (j == 0 or j == rows - 1) and i != rows - 1: print("*", end=" ") elif i == rows - 1 and j != 0 and j != rows - 1: print("*", end=" ") else: print(" ",end=" ") print()
Python program to print the Alphabet U Star pattern using while loop
Instead of a For loop, this program uses the while loop to iterate the Alphabet U pattern rows and prints the stars on the first row and middle column. For more Star Pattern programs >> Click Here. In this example, we removed extra spaces, squeezed U, and adjusted the code to get the boxy U.
rows = int(input("Enter Alphabet U of Stars Rows = ")) i = 0 while i < rows: j = 0 while j < rows: if (j == 0 or j == rows - 1) and i != rows: print("*", end="") elif i == rows - 1 and j != 0 and j != rows: print("*", end="") else: print(end=" ") j += 1 print() i += 1
Enter Alphabet U of Stars Rows = 10
* *
* *
* *
* *
* *
* *
* *
* *
* *
**********
In this Python example, we created an UPattern function that accepts the rows and the symbol or character to print the Alphabet U pattern of the given symbol.
def UPattern(rows, ch): for i in range(rows): for j in range(rows): if (j == 0 or j == rows - 1) and i != rows - 1: print('%c' %ch, end=' ') elif i == rows - 1 and j != 0 and j != rows - 1: print('%c' %ch, end=' ') else: print(" ", end=" ") print() row = int(input("Enter Alphabet U of Stars Rows = ")) sy = input("Symbol for U Star Pattern = ") UPattern(row, sy)
Enter Alphabet U of Stars Rows = 13
Symbol for U Star Pattern = @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @ @ @ @ @ @ @ @ @ @