本文介绍了如何使用 for 循环、while 循环和函数编写一个 Python 程序来打印字母 B 星型图案,并附带示例。
下面的字母 B 星型图案示例接受用户输入的行数,并通过嵌套的 for 循环进行迭代。Else If 或 elif 条件用于在某些位置打印星号,从而得到字母 B 图案的星号,并跳过其他位置。
rows = int(input("Enter Alphabet B of Stars Rows = "))
print("====The Alphabet B Star Pattern====")
for i in range(rows):
print('*', end='')
for j in range(2 * rows - 1):
if (i == 0 or i == rows - 1 or i == rows // 2) and j < (2 * rows) - 2:
print('*', end='')
elif j == (2 * rows) - 2 and not (i == 0 or i == rows - 1 or i == rows // 2):
print('*', end='')
else:
print(end=' ')
print()
Enter Alphabet B of Stars Rows = 7
====The Alphabet B Star Pattern====
*************
* *
* *
*************
* *
* *
*************
上面的代码生成了字母 B,但你也可以尝试下面的代码,它看起来比上面的代码更好。
rows = int(input("Enter Alphabet B of Stars Rows = "))
print("====The Alphabet B Star Pattern====")
n = rows // 2
for i in range(rows):
print('*', end='')
for j in range(n + 1):
if (i == 0 or i == rows - 1 or i == n) and j < n:
print('*', end='')
elif j == n and not (i == 0 or i == rows - 1 or i == n):
print('*', end='')
else:
print(end=' ')
print()

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