简体   繁体   English

Python嵌套循环三角形

[英]Python nested loop triangle

The output I am trying to achieve is : 我想要实现的输出是:

##
# #
#  #
#   #
#    #
#     #

The code I have is : 我的代码是:

NUM_STEPS = 6

for r in range(NUM_STEPS):
   for c in range(r):
      print(' ', end='')
   print('#','\t')
   print('#')   

Its close, but not quite the output I am trying to achieve. 它接近但不是我想要实现的输出。 Any help or suggestions are most appreciated. 任何帮助或建议,我们将不胜感激。

The main thing is you should use '+' (or concat) to build up a string before printing it. 最主要的是您应该在打印之前使用'+'(或concat)构建字符串。 You can eliminate the inner loop by using '*' to make r spaces, which cleans things up a lot. 您可以通过使用'*'来消除内部循环,从而使r空格消除,从而可以将内容清理很多。

NUM_STEPS = 6
for r in range(NUM_STEPS):
    print("#" + (' ' * r) + "#")

This seemed to work when I tried it: 当我尝试时这似乎起作用:

for r in range(NUM_STEPS):
    print("#", end = "")
    for c in range(r):
        print(" ", end = "")
    print("#")

I hope it helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM