Python 打印 U 星形图案程序

本文介绍了如何使用 for 循环、while 循环和函数(带示例)编写 Python 程序来打印字母 U 星形图案。

下面的字母 U 星形图案示例接受用户输入的行数,嵌套的 for 循环会迭代行。elif 条件用于在第一列和最后一列以及最后一行打印星形,以获得字母 U 形的星形图案并跳过其他。

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()
Program to Print Alphabetical U Star Pattern

使用 while 循环打印字母 U 星形图案的 Python 程序

此程序使用 while 循环来迭代字母 U 图案的行,并在第一行和中间列打印星形,而不是使用 For 循环。有关更多星形图案程序 >> 点击此处。在此示例中,我们删除了多余的空格,压缩了 U,并调整了代码以获得方形 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
*        *
*        *
*        *
*        *
*        *
*        *
*        *
*        *
*        *
**********

在此 Python 示例中,我们创建了一个 UPattern 函数,该函数接受行数和要打印给定符号的字母图案的字符。

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 = @
@                       @ 
@                       @ 
@                       @ 
@                       @ 
@                       @ 
@                       @ 
@                       @ 
@                       @ 
@                       @ 
@                       @ 
@                       @ 
@                       @ 
  @ @ @ @ @ @ @ @ @ @ @