本文展示了如何使用 for 循环、while 循环和函数编写一个 Python 程序来打印字母 A 星形图案,并附带示例。
下面的字母 A 星形图案示例接受用户输入的行数,嵌套的 for 循环会迭代行。If else 条件用于在某些位置打印星号,从而获得字母 A 的星形图案,而跳过其他位置。
rows = int(input("Enter Alphabet A of Stars Rows = "))
for i in range(rows):
for j in range(rows // 2 + 1):
if (i == 0 and j != 0 and j != rows // 2) or i == rows // 2 or (j == 0 or j == rows // 2) and i != 0:
print('*', end='')
else:
print(end=' ')
print()
Enter Alphabet A of Stars Rows = 9
***
* *
* *
* *
*****
* *
* *
* *
* *
上面的示例看起来不错;但是,我们必须稍微修改程序以获得完美的字母 A 星形图案。
rows = int(input("Enter Alphabet A of Stars Rows = "))
print("====The Alphabet A Star Pattern====")
n = rows
for i in range(rows):
for j in range(2 * rows):
if j == n or j == ((2 * rows) - n) or (i == (rows // 2) and n < j < ((2 * rows) - n)):
print('*', end='')
else:
print(end=' ')
print()
n = n - 1

使用 while 循环打印字母 A 星形图案的 Python 程序
此程序使用 while 循环迭代 A 图案的行,并在每个位置打印星号,而不是使用 for 循环。有关更多星形图案程序,请点击此处。
rows = int(input("Enter Alphabet A of Stars Rows = "))
n = rows
i = 0
while i < rows:
j = 0
while j < 2 * rows:
if j == n or j == ((2 * rows) - n) or (i == (rows // 2) and n < j < ((2 * rows) - n)):
print('*', end='')
else:
print(end=' ')
j = j + 1
print()
i = i + 1
n = n - 1
Enter Alphabet A of Stars Rows = 10
*
* *
* *
* *
* *
***********
* *
* *
* *
* *
在此示例中,我们创建了一个 APattern 函数,该函数接受行数和要打印的符号或字符,以打印给定符号的字母 A 图案。
def APattern(rows, ch):
n = rows
for i in range(rows):
for j in range(2 * rows):
if j == n or j == ((2 * rows) - n) or (i == (rows // 2) and n < j < ((2 * rows) - n)):
print('%c' %ch, end='')
else:
print(end=' ')
print()
n = n - 1
row = int(input("Enter Alphabet A of Stars Rows = "))
sym = input("Symbol for A Pattern = ")
APattern(row, sym)
Enter Alphabet A of Stars Rows = 9
Symbol for A Pattern = $
$
$ $
$ $
$ $
$$$$$$$$$
$ $
$ $
$ $
$ $