Py学习  »  Python

在python中如何使用while?

Y T Lin Alex • 5 年前 • 1409 次点击  

我只能用 while print 完成作业。我尝试了不同的方法来处理这个问题,但还是坚持了下来。

预期产量:

          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

我得到的是:

          1
        1 2
      1 2 3
    1 2 3 4
  1 2 3 4 5
1 2 3 4 5 6

这是我的代码:

j = 1
i = 1
t = 6
x = 10
d = 1
while i <= 6:
    n = 1
    space = -3
    while space <= j:
        print(" " * x, end="")
        space += 1
        break
    while n <= i:
        print('%d '%n, end="")
        n += 1
    print("")
    i += 1
    x -= 2
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50542
 
1409 次点击  
文章 [ 3 ]  |  最新文章 5 年前
Asif
Reply   •   1 楼
Asif    5 年前

您必须按与当前打印相反的顺序打印:

n =6
i = 1
tCol = n*2 -1
while i <=n:
    cCount = i*2
    spaceCount = tCol - cCount +1
    s=1
    while s<=spaceCount:
        print(" ",end="")
        s+=1
    t =i
    while t>=1:
        print(t, end="")
        if(t!=1):
            print(" ", end="")
        t-=1
    print()

    i+=1

输出:

          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

你可以把n的值改为任意数字

Selcuk
Reply   •   2 楼
Selcuk    5 年前

你就快到了。倒数就行了,也就是说,换下一行

n = 1

n = i

while n <= i:
    print('%d '%n, end="")
    n += 1

while n > 0:
    print('%d '%n, end="")
    n -= 1

也可以尝试一行解决方案来获得乐趣:

>>> print("\n".join([" " * (7 - i) * 2 + " ".join([str(x) for x in reversed(range(1, i))]) for i in range(2, 8)]))
ComplicatedPhenomenon
Reply   •   3 楼
ComplicatedPhenomenon    5 年前
x = [i for i in range(1, 7)]
n = len(x)
j =1 
while j <= n:
    print('  '*(n-j), end="")
    print(*x[0:j][::-1])
    j +=1 

输出

          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1