如何使用嵌套 for 循环打印右对齐三角形(无字符串加法或乘法)

问题描述 投票:0回答:2

这段代码可以工作,但它继续给我一个金字塔而不是右对齐的三角形。 例如: 我正在尝试这样的事情:

    *
   **
  ***
 ****
*****

这是我的代码

height = int(input("What is your height: "))

count = 1
space_count = height
for rows in range (height):
    for spaces in range (space_count):
        print(end=' ')
    for stars in range (count):
        print ("*", end=' ')
    space_count = space_count - 1
    count = count + 1

    print()
python ascii
2个回答
0
投票

金字塔问题来自两个方面: (1) 第一次打印时根本不打印任何内容;尝试

print (" ", end=' ')

这将为您提供一个三角形,但插入了空格:

What is your height: 5
          * 
        * * 
      * * * 
    * * * * 
  * * * * * 

要消除中间的空格,请切换到格式化打印。简单的打印会自动在输出字段之间留出一个空格。


0
投票

不使用字符串加法或乘法:

height = int(input("What is your height: "))
for row in range(height):
    for s in range(height-row-1):
        print(end=' ')
    for a in range(row+1):
        print('*', end='')
    print()

但是,我建议使用以下其中一种以避免多个嵌套循环。

以下内容将为每行打印

height-row-1
空格(第一行从 4 开始,最后一行为 0),后跟
row+1
星号(第一行从 1 开始,最后一行为 0)最后一行为 5):

height = int(input("What is your height: "))
for row in range(height):
    print(' '*(height-row-1) + '*'*(row+1))

您还可以使用字符串方法。

rjust()
方法将在
height
字符的固定宽度字段中右对齐给定字符串(在本例中,是给定行的适当数量的星号)。

height = int(input("What is your height: "))
for row in range(height):
    print(((row+1)*'*').rjust(height))

或者字符串格式化,其工作原理与上面的方法类似,只是它使用字符串格式化迷你语言

height = int(input("What is your height: "))
for row in range(height):
    print(('{:>'+str(height)+'}').format('*'*(row+1)))
© www.soinside.com 2019 - 2024. All rights reserved.