如何使用for循环创建直角三角形?

时间:2016-10-11 12:36:32

标签: python

I want to print :
    1
   12
  123
 1234

我试过了:

num=int(input("number"))
space=int(num)
count=1
while count<num:
  if count==1:
    print(" "*space,count)
    count=count+1
    space=space-1
    while count>=2:
      for n in range(2,num):
        print(" "*space,list(range(1,n))
        space=space-1

但它不起作用。 我该如何打印指定的结果? 感谢

1 个答案:

答案 0 :(得分:0)

print(" "*space,list(range(1,n))

计算此行的括号。其中一个没有关闭,它必须按照你的意图工作。

另请注意,while循环永远不会停止运行。

作为一般经验法则,只要您确切知道应该做多少次,就应该使用for循环而不是while循环

让我们尝试使用for循环重写代码:

num=int(input("number"))
output = ""
for n in range(1,num+1):
    output = ''.join([output, str(n)])
    space = ' ' * (num - len(output))
    print(space, output, sep='')

除了for循环之外,我做的唯一真正的实质性更改是将输出视为字符串而不是数字列表。

相关问题