本文展示了如何使用 for 循环、while 循环和函数以及示例编写一个 Python 程序来打印字母 R 星形图案。
下面的字母 R 星形图案示例接受用户输入的行数,并且嵌套的 for 循环迭代这些行。elif 条件用于在几个所需位置打印星号,以获得字母 R 星形图案并跳过其他。
rows = int(input("Enter Alphabet R of Stars Rows = "))
print("====The Alphabet R Star Pattern====")
for i in range(rows):
for j in range(rows):
if i == 0 and 0 < j < rows - 1:
print("*", end="")
elif i != 0 and j == 0:
print("*", end="")
elif i == rows // 2 and j != rows - 1:
print("*", end="")
elif i != 0 and j == rows - 1 and i < rows // 2:
print("*", end="")
elif i == j and i >= rows // 2:
print("*", end="")
else:
print(end=" ")
print()
Enter Alphabet R of Stars Rows = 9
====The Alphabet R Star Pattern====
*******
* *
* *
* *
********
* *
* *
* *
* *
下面的代码减少了打印字母 R 星形图案的 else if 条件的数量。我们添加了额外的空格,使(R)看起来更好。
rows = int(input("Enter Alphabet R of Stars Rows = "))
print("====The Alphabet R 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 i != 0 and (j == 0 or (j == rows - 1 and i < rows // 2)):
print("*", end=" ")
elif i == j and i >= rows // 2:
print("*", end=" ")
else:
print(" ", end=" ")
print()

使用 while 循环打印字母 R 星形图案的 Python 程序
此程序使用 while 循环来迭代字母 R 图案的行,并在所需位置打印星号,而不是使用 For 循环。更多星形图案程序 >> 点击这里。
rows = int(input("Enter Alphabet R 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 i != 0 and (j == 0 or (j == rows - 1 and i < rows // 2)):
print("*", end=" ")
elif i == j and i >= rows // 2:
print("*", end=" ")
else:
print(" ", end=" ")
j += 1
print()
i += 1
Enter Alphabet R of Stars Rows = 12
* * * * * * * * * *
* *
* *
* *
* *
* *
* * * * * * * * * * *
* *
* *
* *
* *
* *
在此程序示例中,我们创建了一个 RPattern 函数,该函数接受行数和要打印的符号或字符,以打印给定符号的字母 R 图案。
def RPattern(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 i != 0 and (j == 0 or (j == rows - 1 and i < rows // 2)):
print('%c' %ch, end=' ')
elif i == j and i >= rows // 2:
print('%c' %ch, end=' ')
else:
print(" ", end=" ")
print()
row = int(input("Enter Alphabet R of Stars Rows = "))
sy = input("Symbol for R Star Pattern = ")
RPattern(row, sy)
Enter Alphabet R of Stars Rows = 15
Symbol for R Star Pattern = @
@ @ @ @ @ @ @ @ @ @ @ @ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @ @ @ @ @ @ @ @ @ @ @ @ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @