金字塔的星星使用而循环python嵌套而循环

时间:2016-03-17 23:58:04

标签: python loops python-3.x while-loop

过去两天我一直在努力尝试使用来自用户输入的while循环制作金字塔金字塔

最终结果的示例如下所示:

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

但我甚至不清楚这是怎么回事。正如我在过去两个晚上一直试图解决这个问题。

到目前为止,这就是我的全部内容:

userInput = int(input("Please enter the amount of rows: "))
count = 1
spacing = 0
actualStars = "*"
numberStars = 0
rows = 0
while(userInput <= rows):
    rows += count
    print()
    while(spacing <= userInput):
        spacing += count
        print(" ")
        while(numberStars <= 0):
            print(actualStars)

4 个答案:

答案 0 :(得分:2)

由于这是作业,而不是给你一个代码答案,我将概述一下这应该如何运作。鉴于三个循环的约束,这似乎是预期的:

  1. 第一个外循环应遍历行。第一遍产生第一行,第二遍产生第二行,等等。

  2. 第二个循环嵌套在第一个循环中。它为当前行生成前导空格。

  3. 第三个循环也嵌套在第一个循环中,但不是第二个循环。它在第二个循环之后执行,并且应该在代码中跟随它。它为当前行生成星星。

  4. 这些循环中的每一个都非常简单,你应该没有问题。唯一棘手的部分是让print打印一个字符串,而不使用换行符(结束当前行)。如果您正在使用Python 3,则可以使用print("abc", end="")执行此操作。这将打印字符串abc,但不会结束该行。在第三个循环之后,需要结束该行,您可以使用print()

答案 1 :(得分:0)

我在您的代码中看到的一些直接问题

    不执行print(' ')
  • print(' ', end='')将打印换行符,但在您打印完所有空格和星标之前,您不希望这样做
  • while(userInput <= rows)除非您输入非正数,否则自rows = 0
  • 以来不会运行
  • 每次打印空间时,都会打印星星。这是不正确的,因为你需要打印空格和然后明星

这是正确的代码。另请注意,对于第1行,第2行,第3行,金字塔有1颗星,3颗星,5颗星等。这可以概括为2*row-1颗星

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()

实施例

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

答案 2 :(得分:0)

所以,让我们在算术上接近这个。第一行需要一颗星,第二行需要两颗星,第三行需要三颗星等。

换句话说,星数等于当前行索引(假设您将索引设置为1)。 Python的字符串格式方法允许您指定居中的字符串,您可以将星号乘以行索引,因为Python中的字符串实现了乘法协议 mul

i = 0
rows = 8
while i <= rows:
  print("{:^8}".format("*"*i))
  i += 1

这将输出以下内容:

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

正如你所看到的,它有点不平衡,但我们正走在正确的轨道上。它是不平衡的,因为“列”的数量是偶数,当有奇数个星时,它们不能居中。如果我们有奇数列,则会发生完全相反的情况。

那么,我们如何将这些中心化?有几种方法可以接近它,但我只是通过在每颗恒星之间打印一个空格来使每一排星都变得奇怪。在这一点上,他们完全居中。

您需要做的就是添加另外两个循环:

1)复制format()模板的空白填充

2)通过在星星之间放置一个空格来创建'true'居中的字符串

这可以通过三个while循环完成,但我不知道它是如何pythonic。但我没有写作业:)

HTH

答案 3 :(得分:0)

userInput=int(input("Please enter the amount of rows:"))
row=""
count =1
spacing =0
star=0
u=0
while(count <=userInput):
    spacing =spacing +count 
    while(spacing<userInput):
        row+=" "
        spacing +=1
    star=count +u
    while(star>0):
        row+="*"
        star-=1
    count +=1
    spacing=0
    u+=1
    print(row)
    row*=-1