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

How do I print the following pattern using nested loops in python?

我是 python 的初学者,过去 40 分钟我一直在尝试打印它。任何有关我如何做到这一点的帮助将不胜感激。 第一行有11个空格,第二行有7个空格,第三行有3个空格,最后一行没有空格。

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

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

打印:

this. 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

希望我帮到了你