本文将介绍如何使用for循环、while循环和函数编写一个Python程序来打印字母M星形图案,并提供示例。
下面的字母M星形图案示例接受用户输入的行数,嵌套的for循环会迭代行。If else条件用于在第一列和最后一行打印星形,以形成字母M的星形图案,并跳过其他位置。
rows = int(input("Enter Alphabet M of Stars Rows = "))
print("====The Alphabet M Star Pattern====")
for i in range(rows):
print("*", end="")
for j in range(rows + 1):
if j == rows or (j == i - 1 and j < rows // 2) or (j == rows - i and j > rows // 2):
print("*", end="")
else:
print(end=" ")
print()
Enter Alphabet M of Stars Rows = 9
====The Alphabet M Star Pattern====
* *
** **
* * * *
* * * *
* * * *
* *
* *
* *
* *
如果您想要在M图案的奇数行添加额外的*,请在for循环的上方使用以下代码。
if rows % 2 != 0:
rows += 1
此代码是编写字母M星形图案的另一种版本。
rows = int(input("Enter Alphabet M of Stars Rows = "))
print("====The Alphabet M Star Pattern====")
for i in range(rows):
print("*", end="")
for j in range(rows + 1):
if j == rows or (j == i and j < rows // 2) or (j == rows - i - 1 and j > rows // 2):
print("*", end="")
else:
print(end=" ")
print()

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