本文展示了如何使用 for 循环、while 循环和带有示例的函数编写 Python 程序来打印字母 Y 星形图案。
下面的 Y 字母星形图案示例接受用户输入的行数,嵌套的 for 循环迭代这些行。 If else 条件用于在所需位置打印星号,以获得字母 Y 星形图案并跳过其他位置。
rows = int(input("Enter Alphabet Y of Stars Rows = "))
print("====The Alphabetical Y Star Pattern====")
for i in range(rows):
for j in range(rows):
if (i + j == rows - 1) or (i == j and i < rows / 2):
print("*", end=" ")
else:
print(" ", end=" ")
print()
Enter Alphabet Y of Stars Rows = 9
====The Alphabetical Y Star Pattern====
* *
* *
* *
* *
*
*
*
*
*
上面的代码打印了字母 Y 星形图案,但这个 Python 示例比上面的更好。
rows = int(input("Enter Alphabet Y of Stars Rows = "))
print("====The Alphabetical Y Star Pattern====")
if rows % 2 == 0:
rows += 1
for i in range(rows):
for j in range(rows):
if (i + j == rows - 1 or i == j) and (i < rows // 2) or (j == rows // 2 and i > rows // 2 - 1):
print("*", end=" ")
else:
print(" ", end=" ")
print()

使用 while 循环打印字母 Y 星形图案的 Python 程序
与 For 循环不同,此程序使用 while 循环来迭代字母 Y 图案的行,并在几个位置打印星号。有关更多星形图案程序 >> 点击此处。
rows = int(input("Enter Alphabet Y of Stars Rows = "))
if rows % 2 == 0:
rows += 1
i = 0
while i < rows:
j = 0
while j < rows:
if (i + j == rows - 1 or i == j) and (i < rows // 2) or (j == rows // 2 and i > rows // 2 - 1):
print("*", end=" ")
else:
print(" ", end=" ")
j += 1
print()
i += 1
Enter Alphabet Y of Stars Rows = 11
* *
* *
* *
* *
* *
*
*
*
*
*
*
在这个 Python 示例中,我们创建了一个 YPattern 函数,该函数接受行数和要打印给定符号的字母图案的符号或字符。
def YPattern(rows, ch):
for i in range(rows):
for j in range(rows):
if (i + j == rows - 1 or i == j) and (i < rows // 2) or (j == rows // 2 and i > rows // 2 - 1):
print('%c' %ch, end=' ')
else:
print(" ", end=" ")
print()
row = int(input("Enter Alphabet Y of Stars Rows = "))
sy = input("Symbol for Y Star Pattern = ")
if row % 2 == 0:
row += 1
YPattern(row, sy)
Enter Alphabet Y of Stars Rows = 14
Symbol for Y Star Pattern = #
# #
# #
# #
# #
# #
# #
# #
#
#
#
#
#
#
#
#