私信  •  关注

Asif

Asif 最近回复了
5 年前
回复了 Asif 创建的主题 » 在python中如何使用while?

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

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的值改为任意数字

对于写入文件,float需要转换成字符串,而newline需要逐行写入。下面是编写浮动的示例:

sd = [1.34, 45.5768] . # list of floats
with open('fileName.txt', 'a') as fd:
    for d in sd:
        fd.writelines(str(d))
        fd.writelines("\n")

输出:

1.34
45.5768

在代码中,您可以这样修改:

    fd.writelines(str(si))
    fd.writelines("\n")