簡體   English   中英

Python 3居中三角形

[英]Python 3 centered triangle

我正在嘗試通過良好的舊三角練習(目前僅需要輸入奇數)來磨練我的Python 3(特別是嵌套循環)。 但是,我遇到了一個我無法解決的問題。

user_input = 7
x = 1
temp = user_input
spaces = " "
stars = ""
y = temp - 2
t = 0
while x < temp:
    while y > t:
        stars = "*" * x
        spaces = spaces * y
        print(spaces + stars)
        spaces= " "
        y -= 1
        x += 2

我有一個user_input (現在是7,所以我每次運行時都不必輸入)。

用於while循環的變量xt

另一個保存我的user_input temp變量(以防我減少它以免“損壞”原始變量)。

一個可變的spaces和另一個可變的stars (這在我試圖根據星號繪制三角形時應該是不言而喻的)。

我有一個等於temp - 2的變量y

預期的輸出7應該是這樣的:

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

之所以將y等於temp - 2是因為第一行的空格等於user_input - 2

假設我們的輸入為7,第一行的空間為5。

如果我們的輸入為9,則第一行的空格數為7

第一個while循環將從1循環到7(1、3、5、7),這就是為什么我使x等於1

第二個while循環應從input - 2一直循環到0。

奇怪的是,如果我的user_input等於5 ,它將輸出我所期望的樣子。

   *
  ***
 *****

但是一旦我輸入類似7東西,它就會建立一個從1到9的三角形(1、3、5、7、9)

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

但是我希望它在最后一行之前結束,它應該輸出與我輸入的一樣多的星號。

我的思考過程錯了嗎? 如果是這樣,我哪里錯了?

我希望我已盡一切可能澄清。

謝謝你

似乎過於復雜。 為什么不只是:

input = 7
i = 1
while i <= input:
    spaces = ' ' * ((input-i) // 2) 
    stars = '*' * i
    print(spaces + stars)
    i += 2 

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

甚至更簡單,使用str.center

while i <= input:
    print(('*' * i).center(input))
    i += 2

讓我們來澄清一下您的代碼:

  • t是無用的,因為它僅持有0且永不更改,請改用0
  • user_input是從來沒有使用過,除了使temp = user_input ,使用user_input ,而不是臨時的。 至於遞減,它不會發生,而且無論如何您都不會將它退還給用戶,這樣就可以了。
  • 有點錯,所以可以,但是在Stack Overflow上顯示某些代碼時,避免讓調試打印像print(x,y)一樣,我們很難理解整個代碼。
  • 如果更改回spaces = " "在結束while ,只需使用spaces = " " * y
  • 在這兩者之間您什么也沒做while因此可以使用and條件將它們“合並”。

現在我們有了:

user_input = 9
x = 1
y = user_input - 2
while x < user_input and y > 0:
    stars = "*" * x
    spaces = " " * y
    print(spaces + stars)
    y -= 1
    x += 2

如您所見,您只有兩個停車條件, while只有一個停車條件會更清晰。 您的代碼使用7而不是更多的原因是因為7是一個條件停止循環與另一個條件停止循環之間的限制。

我建議將您的代碼更改為:

user_input = 3
x = 0
while x < user_input//2:
    stars = "*" * (x * 2 + 1)
    spaces = " " * (user_input//2 - x)
    print(spaces + stars)
    x += 1

您的代碼中有一個錯誤。 這是更正的代碼。

user_input = 7
x = 1
temp = user_input
spaces = " "
stars = ""
y = temp - 2
t = 0
while x <= temp:
    stars = "*" * x
    spaces = spaces * y
    print(spaces + stars)
    spaces= " "
    y -= 1
    x += 2

不需要檢查y>0因為您的第一個while循環足以滿足要求。 由於存在額外的while loop您得到了(x,y)模棱兩可的值。

使用內置center()mini語言格式的惰性解決方案:

user_input = [5,7,9]

def getStars(num):
    return ('*' * i for i in range(1,num+1,2))

def sol1(num):
    for s in getStars(num):
        print(s.center(num)) 

def sol2(num):
    stars = getStars(num)

    for s in stars:
        print( ("{:^"+str(num)+"}").format(s))

for s in user_input:
    sol1(s)
    sol2(s) 

輸出:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM