python - For/While 循环生成 *-三角形

标签 python python-3.x

对于编码类(class)中的作业,我应该找到一种方法让 Python 制作星号三角形,如下所示:

   x
  xx
 xxx 

但是,无论我用我的代码做什么,我都无法做到这一点。最好的我 可以得到的是:

x
xx
xxx 

所有这些都必须只使用 for 循环和 while 循环,就像我在这里使用的那样。我使用的代码是

for a in range(1, 15):
 for a2 in range(14-a, 0, 1):
     print(" ", end='')
 for a1 in range(1, a+ 1):
     print("*", end='')
 print()

- 代表缩进。我如何按照我想要的方式进行这项工作?

编辑:事实证明,我只注意到了一半的问题。我最终使用的代码在这里生成了我需要的两个三角形,但将它们一个堆叠在另一个下方。我现在遇到的问题是让它们并排出现,就像 M 形一样。

for b in range(1, 10):
    for b2 in range(9-b, 0, 1):
        print(" ", end='')    
    for b1 in range(1, b+ 1):
        print("*", end='')
    print()

for a in range(1, 10):
    for a2 in range(9-a, 0, -1):
        print(" ", end='')
    for a1 in range(1, a+ 1):
        print("*", end='')
    print()

我知道我错过了什么,只是看不到它是什么。

最佳答案

以下是仅使用 for 循环解决这两个问题的方法。这种方法不是很 pythonic,但这是您所要求的。

单个三角形问题的解决方案

   x
  xx
 xxx 

你们真的很亲密。当你想从 14-a 下降到 0 时,你写了 1 而不是 -1

for a in range(1, 15):
 for a2 in range(14-a, 0, -1):
     print(" ", end='')
 for a1 in range(1, a+ 1):
     print("*", end='')
 print()

解释(来自 here ):

range(start, stop[, step])

If the step argument is omitted, it defaults to 1. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop.

所以在你的例子中,你原来的 for 循环什么也没做,因为 14-a 不小于 0 并且 step 是正数。

M形问题的解法

 x    x
 xx  xx
 xxxxxx

-

HEIGHT = 3
for b in range(1, HEIGHT+1):
    for a in range(1, b + 1):
        print("*", end='')
    for a in range(0, 2*(HEIGHT-b)):
        print(" ", end='')
    for a in range(1, b + 1):
        print("*", end='')
    print()

关于python - For/While 循环生成 *-三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34109838/

相关文章:

python 3 : "NameError: name ' function' is not defined"

python - 如何检测 Python 是否在 Python 开发模式下运行?

python - 为什么 str.count ('' ) 和 len(str) 给出不同的输出?

python-3.x - python3中的find()方法

python - 在 python 中制作图像 flash

python - Numpy vectorize() 正在展平整个数组

python - 安装pycurl 7.19.0报错

python - 如何移动 matplotlib 图中的一条线?

python - 如何在Python代码中引用反斜杠(四\引用一)?

python - 为什么 gunicorn 使用相同的线程