Python:用数字制作金字塔



我正在尝试制作数字的金字塔,而无需重新分配

我能够用符号做到这一点(请参见下文):

def print_pyramid_step_3(heightNum):
    ctr = 1
    while(ctr <= heightNum):
        row_spaces = " " * (heightNum - ctr)
        row = (2*ctr-1) * "$"
        print(row_spaces + row)
        ctr = ctr +1
# Get the input to get the height of the pyramid
heightNum = int(input("Enter the height of the pyramid: "))
print("----"*50)
print("Printing the pyramid by adding spaces to the row")
print("----"*50)
print_pyramid_step_3(heightNum)

输出:

    $
   $$$
  $$$$$
 $$$$$$$
$$$$$$$$$

当用户在金字塔高度为5中的用户键入5,起始数字为1。

所需的输出:

    1
   234
  56789
 10111213141516
171819202122232425

尝试以下:

j = 1
for i in range(height):
    for k in range(1,height + i+1):
        if (k < height - i):
            print(" ", end='')
        else:
            print(j, end='')
            j+=1
    print()

最新更新