首页 > 解决方案 > 有问题要理解金字塔中的while循环

问题描述

谁能解释如何在 python 中使用 while 循环创建金字塔?

userInput = int(input("Please enter the amount of rows: "))
 row = 0
  while(row < userInput):
   row += 1
   spaces = userInput - row




spaces_counter = 0
while(spaces_counter < spaces):
    print(" ", end='')
    spaces_counter += 1

num_stars = 2*row-1
while(num_stars > 0):
    print("*", end='')
    num_stars -= 1

print()

如果有人向我解释该代码,那就太好了..thx

标签: python

解决方案


你只需要修复你的缩进:

userInput = int(input("Please enter the amount of rows: "))
row = 0
while(row < userInput):
    row += 1
    spaces = userInput - row

    spaces_counter = 0
    while(spaces_counter < spaces):
        print(" ", end='')
        spaces_counter += 1

    num_stars = 2*row-1
    while(num_stars > 0):
        print("*", end='')
        num_stars -= 1

    print()    # next line

输出

Please enter the amount of rows: 5
    *
   ***
  *****
 *******
*********

推荐阅读