本文介绍如何使用 for 循环、while 循环和函数编写 Python 程序来打印字母 J 星形图案,并附带示例。
下面的字母 J 星形图案示例接受用户输入的行数,嵌套的 for 循环会迭代行。elif 条件用于在某些位置打印星号,以获得字母 J 星形图案,并跳过其他位置。
rows = int(input("Enter Alphabet J of Stars Rows = "))
print("====The Alphabet J Star Pattern====")
for i in range(rows):
for j in range(rows):
if i == rows - 1 and (0 < j < rows - 1):
print("*", end="")
elif (j == rows - 1 and i != rows - 1) or (i > rows // 2 and j == 0 and i != rows - 1):
print("*", end="")
else:
print(end=" ")
print()

下面的代码使用 if else 语句打印字母 J 星形图案,图案更直观。
rows = int(input("Enter Alphabet J of Stars Rows = "))
for i in range(rows):
for j in range(rows):
if (i == 0 or j == rows // 2) or (i == rows - 1 and j <= rows // 2):
print("*", end="")
else:
print(end=" ")
print()
Enter Alphabet J of Stars Rows = 13
*************
*
*
*
*
*
*
*
*
*
*
*
*******
Python 使用 while 循环打印字母 J 星形图案的程序
此程序使用 while 循环来迭代字母 J 图案的行,而不是 For 循环,并在每个位置打印星号。有关更多星形图案程序,请参见>> 此处。
rows = int(input("Enter Alphabet J of Stars Rows = "))
i = 0
while i < rows:
j = 0
while j < rows:
if i == rows - 1 and (0 < j < rows - 1):
print("*", end="")
elif (j == rows - 1 and i != rows - 1) or (i > rows // 2 and j == 0 and i != rows - 1):
print("*", end="")
else:
print(end=" ")
j = j + 1
print()
i += 1
Enter Alphabet J of Stars Rows = 9
*
*
*
*
*
* *
* *
* *
*******
在此程序示例中,我们创建了一个 JPattern 函数,该函数接受行数和要打印字母 J 图案的符号或字符。
def JPattern(rows, ch):
for i in range(rows):
for j in range(rows):
if i == rows - 1 and (0 < j < rows - 1):
print('%c' %ch, end='')
elif (j == rows - 1 and i != rows - 1) or (i > rows // 2 and j == 0 and i != rows - 1):
print('%c' %ch, end='')
else:
print(end=" ")
print()
row = int(input("Enter Alphabet J of Stars Rows = "))
sy = input("Symbol for J Star Pattern = ")
JPattern(row, sy)
Enter Alphabet J of Stars Rows = 14
Symbol for J Star Pattern = @
@
@
@
@
@
@
@
@
@ @
@ @
@ @
@ @
@ @
@@@@@@@@@@@@