簡體   English   中英

額外的新行打印 Python

[英]Extra new line on print Python

我有一個小樂趣 function 打印帶有星號的菱形。 它看起來像這樣:

from time import sleep

while True:
    whitespaces_count = 0
    dots_count = 8
    for _ in range(0, 5):
        print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
        whitespaces_count += 2
        dots_count -= 2
        sleep(0.15)
    whitespaces_count = 6
    dots_count = 2
    for _ in range(0, 4):
        print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
        whitespaces_count -= 2
        dots_count += 2
        sleep(0.15)
    print("\n")

它工作正常,但是,在每個print命令之后,它都會打印額外的空白行,所以 output 看起來像這樣:

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

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

但我希望它看起來像這樣:

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


我在做什么錯?

您的問題不是print ,而是您的第一個循環運行了一次額外的時間,不打印點,全是空白。 將其更改為循環range(4)而不是range(5)並且多余的行消失。


旁注:您應該真正利用循環本身來確定要print多少個星號和空格; 您正在使用一個range來決定要運行多少個循環,但它可以執行雙重任務,允許這樣做(最低限度的固定代碼):

whitespaces_count = 0
dots_count = 8
for _ in range(4):
    print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
    whitespaces_count += 2
    dots_count -= 2
    sleep(0.15)

成為:

for whitespaces_count in range(0, 8, 2):
    dots_count = 8 - whitespaces_count
    print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
    sleep(0.15)

或者讓循環做更多的工作,將更多的工作推給性能優於手寫代碼的內置程序(並且dots_count指的是每一邊的點數):

for whitespaces_count, dots_count in zip(range(0, 8, 2), range(4, 0, -1)):
    print("*"*dots_count + " "*whitespaces_count + "*"*dots_count)
    sleep(0.15)

使用for _ in range(0, 5): ,您將比第二個循環多循環一次。 嘗試以下操作:

from time import sleep

while True:
    whitespaces_count = 0
    dots_count = 8
    for _ in range(0, 4):
        print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
        whitespaces_count += 2
        dots_count -= 2
        sleep(0.15)
    whitespaces_count = 6
    dots_count = 2
    for _ in range(0, 4):
        print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
        whitespaces_count -= 2
        dots_count += 2
        sleep(0.15)
    print("\n")

暫無
暫無

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

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