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

使用 while 循环打印字母 W 星形模式的 Python 程序
此程序使用 while 循环来迭代字母 W 模式的行,并打印一些位置的星号,而不是 For 循环。更多星形模式程序 >> 点击此处。
rows = int(input("Enter Alphabet W of Stars Rows = "))
i = 0
while i < rows:
j = 0
while j < rows:
if j == 0 or j == rows - 1:
print("*", end="")
elif (i + j == rows - 1 or i == j) and i >= rows // 2:
print("*", end="")
else:
print("", end=" ")
j += 1
print()
i += 1
Enter Alphabet W of Stars Rows = 10
* *
* *
* *
* *
* *
* ** *
* * * *
* * * *
** **
* *
在此 Python 示例中,我们创建了一个 WPattern 函数,该函数接受行数和符号或字符来打印给定符号的字母 V 模式。
def WPattern(rows, ch):
for i in range(rows):
for j in range(rows):
if j == 0 or j == rows - 1:
print('%c' %ch, end=' ')
elif (i + j == rows - 1 or i == j) and i >= rows // 2:
print('%c' %ch, end=' ')
else:
print(" ", end=" ")
print()
row = int(input("Enter Alphabet W of Stars Rows = "))
sy = input("Symbol for W Star Pattern = ")
WPattern(row * 2 + 1, sy)
Enter Alphabet W of Stars Rows = 8
Symbol for W Star Pattern = @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @ @
@ @ @ @
@ @ @ @
@ @ @ @
@ @ @ @
@ @ @ @
@ @ @ @
@ @ @ @
@ @