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

使用 while 循环打印字母 D 星形图案的 Python 程序
这个程序不使用 For 循环,而是使用 while 循环来迭代字母 D 图案的行。接下来,它会在每个位置打印星形。有关更多星形图案程序,请点击这里:点击此处。
rows = int(input("Enter Alphabet D of Stars Rows = "))
n = rows // 2 + 1
print("*" * n + " " * (rows - 1))
i = 0
while i < (rows - 2):
print("*" + " " * (rows - 2) + "*")
i = i + 1
print("*" * n + " " * (rows - 1))
Enter Alphabet D of Stars Rows = 9
*****
* *
* *
* *
* *
* *
* *
* *
*****
在这个示例中,我们创建了一个 DPattern 函数,该函数接受行数和要打印的符号或字符,以生成给定符号的字母 D 图案。它是上面 D for 循环示例的略微修改版本。
def DPattern(rows, ch):
print('%c' %ch * (rows - 1))
for i in range(rows - 2):
print('%c' %ch + " " * (rows - 2) + '%c' %ch)
print('%c' %ch * (rows - 1))
row = int(input("Enter Alphabet D of Stars Rows = "))
sy = input("Symbol for D Star Pattern = ")
DPattern(row, sy)
Enter Alphabet D of Stars Rows = 12
Symbol for D Star Pattern = @
@@@@@@@@@@@
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@@@@@@@@@@@