本文展示了如何使用 for 循环、while 循环和带示例的函数编写一个 Python 程序来打印字母 Q 星星图案。
下面的字母 Q 星星图案示例接受用户输入的行数,嵌套的 for 循环迭代行。elif 条件用于在四侧打印星星,并带有额外的尾部以获得字母 Q 的星星图案,并跳过其他。
rows = int(input("Enter Alphabet Q of Stars Rows = "))
print("====The Alphabet Q Star Pattern====")
for i in range(rows):
for j in range(rows):
if (i == 0 or i == rows - 2) and (0 < j < rows - 1):
print("*", end=" ")
elif (j == 0 or j == rows - 1) and (0 < i < rows - 2):
print("*", end=" ")
elif (rows // 2 < i < rows) and (rows // 2 < j == i):
print("*", end=" ")
else:
print(" ", end=" ")
print()
Enter Alphabet Q of Stars Rows = 9
====The Alphabet Q Star Pattern====
* * * * * * *
* *
* *
* *
* *
* * *
* * *
* * * * * * *
*
上面的代码使用 elif 条件打印字母 Q 星星图案;下面的代码使用 If else 条件来打印星星。
rows = int(input("Enter Alphabet Q of Stars Rows = "))
print("====The Alphabet Q Star Pattern====")
for i in range(rows):
for j in range(rows):
if (i == 0 or i == rows - 2) and (0 < j < rows - 1) or \
(j == 0 or j == rows - 1) and (0 < i < rows - 2) or \
(rows // 2 < i < rows) and (rows // 2 < j == i):
print("*", end=" ")
else:
print(" ", end=" ")
print()

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