使用嵌套循环绘制三角形

时间:2017-04-03 21:36:33

标签: python-3.x

我正在使用嵌套循环来创建一个反向三角形,该三角形按我输入的任何字符数量下降。例如,如果输入8,我的三角形应该看起来像这样

xxxxxxxx
 xxxxxxx
  xxxxxx
   xxxxx
    xxxx
     xxx
      xx
       x

我的代码目前包含以下内容,但输出并非我所寻找的内容。

row = 1
while row <= size:
    # Output a single row
    col = size - row + 1
    while col <= size:
        # Output the drawing character
        print(end=' ')

        # The next column number
        col = col + 1
    col = 0
    while col <= size - row:
        print(drawingChar, end=' ')
        col = col + 1
    row = row + 1
    print()   
print()

输出:

 x x x x x x x x 
  x x x x x x x 
   x x x x x x 
    x x x x x 
     x x x x 
      x x x 
       x x 
        x 

我确定我用<= size或者某个地方搞砸了一些小事。所有输入都表示赞赏。

1 个答案:

答案 0 :(得分:1)

>>> def foo(n):
...    for i in range(n):
...       print((" "*i) + ("x"*(n-i)))
... 
>>> foo(8)
xxxxxxxx
 xxxxxxx
  xxxxxx
   xxxxx
    xxxx
     xxx
      xx
       x

修改

由于OP要求嵌套循环解决方案,因此它是:

>>> def foo(n):
...    out = ""
...    for i in range(n):
...       for _ in range(i):
...          out += " "
...       for _ in range(n-i):
...          out += "x"
...       out += "\n"
...    print(out)
... 
>>> foo(8)
xxxxxxxx
 xxxxxxx
  xxxxxx
   xxxxx
    xxxx
     xxx
      xx
       x