在这个 Python 程序中,您将学习如何使用 for 循环、while 循环和函数来打印数字 X 图案。下面的示例接受用户输入的行数,嵌套的 for 循环会迭代行和列。接下来,程序中的 if else 语句将以 X 图案打印数字。
rows = int(input("Enter Rows = "))
for i in range(rows):
for j in range(rows):
if i == j or j == rows - 1 - i:
print(j + 1, end='')
else:
print(' ', end='')
print()
Enter Rows = 11
1 11
2 10
3 9
4 8
5 7
6
5 7
4 8
3 9
2 10
1 11
您也可以尝试下面的代码,它会在 X 图案的每一侧打印不同的数字。
rows = int(input("Enter Rows = "))
for i in range(2 * rows - 1):
for j in range(2 * rows - 1):
if i == j or j == 2 * rows - 2 - i:
print(j + 1, end='')
else:
print(' ', end='')
print()
Enter Rows = 9
1 17
2 16
3 15
4 14
5 13
6 12
7 11
8 10
9
8 10
7 11
6 12
5 13
4 14
3 15
2 16
1 17
此 程序 使用 while 循环 来迭代行和列,并打印每个位置的数字 X 图案,而不是 for 循环。更多数字图案程序 >> 点击此处。
rows = int(input("Enter Rows = "))
i = 0
while i < rows:
j = 0
while j < rows:
if i == j or j == rows - 1 - i:
print(j + 1, end='')
else:
print(' ', end='')
j += 1
print()
i += 1
Enter Rows = 15
1 15
2 14
3 13
4 12
5 11
6 10
7 9
8
7 9
6 10
5 11
4 12
3 13
2 14
1 15
这个 Python 程序允许用户输入行数。接下来,XpatternNumber 函数 使用嵌套的 for 循环和 if else 语句,在 X 图案的行和列上打印数字。
def XpatternNumber(rows):
for i in range(rows):
for j in range(rows):
if i == j or j == rows - 1 - i:
print(j + 1, end='')
else:
print(' ', end='')
print()
n = int(input("Enter Rows = "))
XpatternNumber(n)
