如何在python中使用嵌套循环打印以下模式



我是python的初学者,在过去的40分钟里我一直在尝试打印它。如果能为我提供任何帮助,我将不胜感激。第一行有11个空格,第二行有7个空格,第一行有3个空格,最后一行没有空格。

for row in range(4):
for column in range(row + 1):
print(column, end='')
print("")

到目前为止,我有两个循环。这个打印:(图像(另一个是:n = 3 k = 3 for i in range(0,n+1): for j in range(k-i, -1, -1): print(j, end='') print()

打印:

这个。stack.imgur.com/IAIHk.png

我不知道该做什么,但我想我有一个大致的想法。请帮忙!

如果您使用单空间字体,这应该会起作用

for i in range(1, 5):
j = 0
spaces = 2 * (4 - i) - 1
while j < i:
print(j, end = "")
j += 1
if spaces == -1:
j -= 1
else:
print(" " * spaces, end = "")
while j > 0:
j -= 1
print(j, end = "")
print()

如果你想为任何数字做这项工作,你可以定义一个类似的函数

def f(n):
for i in range(1, n + 1):
j = 0
spaces = 2 * (n - i) - 1
while j < i:
print(j, end = "")
j += 1
if spaces == -1:
j -= 1
else:
print(" " * spaces, end = "")
while j > 0:
j -= 1
print(j, end = "")
print()

例如,f(6(将打印

0         0
01       10
012     210
0123   3210
01234 43210
01234543210

希望我能帮助

最新更新