本文介绍了如何使用 for 循环、while 循环和函数编写 Python 程序来打印字母 S 星形图案,并附有示例。
下面的字母 S 星形图案示例接受用户输入的行数,嵌套的 for 循环会遍历这些行。elif 条件用于在第一行、中间行和最后一行,以及第一列和最后一列的一半位置打印星号,以形成字母 S 的星形图案,并跳过其他位置。
rows = int(input("Enter Alphabet S of Stars Rows = "))
print("====The Alphabet S Star Pattern====")
for i in range(rows):
for j in range(rows):
if i == 0 or i == rows // 2 or i == rows - 1:
print("*", end=" ")
elif (j == 0 and i < rows // 2) or (j == rows - 1 and i > rows // 2):
print("*", end=" ")
else:
print(" ",end=" ")
print()
Enter Alphabet S of Stars Rows = 9
====The Alphabet S Star Pattern====
* * * * * * * * *
*
*
*
* * * * * * * * *
*
*
*
* * * * * * * * *
上面的代码会打印出方形的 S。但是下面的代码会打印出更圆润的字母 S 星形图案。
rows = int(input("Enter Alphabet S of Stars Rows = "))
print("====The Alphabet S Star Pattern====")
for i in range(rows):
for j in range(rows):
if (i == 0 or i == rows // 2 or i == rows - 1) and j != 0 and j != rows - 1:
print("*", end=" ")
elif i != 0 and j == 0 and i < rows // 2:
print("*", end=" ")
elif j == rows - 1 and i > rows // 2 and i != rows - 1:
print("*", end=" ")
else:
print(" ", end=" ")
print()

使用 while 循环打印字母 S 星形图案的 Python 程序
此程序不使用 For 循环,而是使用 while 循环来迭代字母 S 图案的行,并在需要的位置打印星号。更多星形图案程序请 >> 点击此处。
rows = int(input("Enter Alphabet S of Stars Rows = "))
i = 0
while i < rows:
j = 0
while j < rows:
if i == 0 or i == rows // 2 or i == rows - 1:
print("*", end=" ")
elif (j == 0 and i < rows // 2) or (j == rows - 1 and i > rows // 2):
print("*", end=" ")
else:
print(" ",end=" ")
j += 1
print()
i += 1
Enter Alphabet S of Stars Rows = 11
* * * * * * * * * * *
*
*
*
*
* * * * * * * * * * *
*
*
*
*
* * * * * * * * * * *
在此 Python 示例中,我们创建了一个 SPattern 函数,该函数接受行数和要打印的符号或字符,以打印给定符号的字母图案。它与第二个示例相同,但我们将 j != rows – 1 替换为 j != rows,并将 j != 0 替换为 j != -1,以使 S 具有正确的结尾。
def SPattern(rows, ch):
for i in range(rows):
for j in range(rows):
if i == 0 and j != 0 and j != rows:
print('%c' % ch, end=" ")
elif i != 0 and j == 0 and i < rows // 2:
print('%c' %ch, end=" ")
elif i == rows // 2 and j != 0 and j != rows - 1:
print('%c' %ch, end=" ")
elif j == rows - 1 and i > rows // 2 and i != rows - 1:
print('%c' %ch, end=" ")
elif i == rows - 1 and j != -1 and j != rows - 1:
print('%c' %ch, end=" ")
else:
print(" ", end=" ")
print()
row = int(input("Enter Alphabet S of Stars Rows = "))
sy = input("Symbol for S Star Pattern = ")
SPattern(row, sy)
Enter Alphabet S of Stars Rows = 12
Symbol for S Star Pattern = #
# # # # # # # # # # #
#
#
#
#
#
# # # # # # # # # #
#
#
#
#
# # # # # # # # # # #