如何打印一个倒三角,正确分类?

发布于 2025-02-14 00:07:57 字数 355 浏览 3 评论 0原文

***
 **
  *

这就是我试图让Python打印的方法。 条件如下: 1。必须使用嵌套循环或更多。

我已经用以下代码解决了此问题:

n = 0
for i in range(3,0,-1):
    print(" "*n ,end = "")
    n+=1
    for j in range(0,i):
        print("*", end="")
    print()

但是,我试图查看是否可以在不声明“ n'varible 的情况下获得相同的输出 。 有办法这样做吗?

***
 **
  *

This is what I'm trying to get python to print.
The conditions are the following:
1. must use nested loops or more.

I've solved this with the following code:

n = 0
for i in range(3,0,-1):
    print(" "*n ,end = "")
    n+=1
    for j in range(0,i):
        print("*", end="")
    print()

However, I'm trying to see if I can get the same output without declaring the 'n' variable.
Is there a way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

稍尽春風 2025-02-21 00:07:57

您可以像这样利用str.rjust():

WIDTH = 3

stars = '*' * WIDTH

print('\n'.join(stars[i:].rjust(WIDTH) for i in range(WIDTH)))

输出:

***
 **
  *

You could take advantage of str.rjust() like this:

WIDTH = 3

stars = '*' * WIDTH

print('\n'.join(stars[i:].rjust(WIDTH) for i in range(WIDTH)))

Output:

***
 **
  *
情栀口红 2025-02-21 00:07:57

我已经解决了以下内容:

for i in range(3): 
  for j in range(i):
   print(' ', end = '')
  for j in range(3-i): 
    print('*', end='')
  print()

I've solved this with the following:

for i in range(3): 
  for j in range(i):
   print(' ', end = '')
  for j in range(3-i): 
    print('*', end='')
  print()
蓝戈者 2025-02-21 00:07:57
def printTriangle(columns:int):
    return "".join([" "*space+"*"*(columns-space)+"\n" for space in range(1+columns)])
    
print(printTriangle(5))

>>> *****
>>>  ****
>>>   ***
>>>    **
>>>     *
def printTriangle(columns:int):
    return "".join([" "*space+"*"*(columns-space)+"\n" for space in range(1+columns)])
    
print(printTriangle(5))

>>> *****
>>>  ****
>>>   ***
>>>    **
>>>     *
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文