[英]python 3.x overwrite previous terminal line
我寫了一個簡單的程序來計算擲骰子的平均結果(毫無意義,但是您必須從某處開始; P):
import random, time
from random import randrange
count = 0
total = 0
one_count = 0
for x in range(10000000):
random = randrange(1,7)
count = count + 1
total = total + random
average = total / count
percentage = one_count / count * 100
if random == 1:
one_count = one_count + 1
print("the percentage of ones occurring is", percentage, "and the average outcome is", average)
# time.sleep(1)
為了清理它,我希望輸出覆蓋前一行。 我嘗試了所有可能找到的內容,但是我唯一想做的就是將最后一行更改為:打印到同一行而不擦除以前的內容:
print("the percentage of ones occuring is", percentage, "and the average outcome is", average, "/// ", end="")
輸出:
the percentage of ones occuring is 0.0 and the average outcome is 4.0 /// the percentage of ones occuring is 0.0 and the average outcome is 4.5 /// the percentage of ones occuring is 0.0 and the average outcome is 3.6666666666666665 ///
有任何想法嗎?
在末尾添加\\r
。 這樣,您編寫的下一行將從上一行的開頭開始。 然后刷新輸出,以便立即顯示。
注意:如果下一行較短,則其余字符仍在那里。
使用end='\\r
:
for x in range(100000):
rnd = randrange(1,7) # don't use random
count += 1
total = total + rnd
average = total / count
percentage = one_count / count * 100
if rnd == 1:
one_count += 1
print("the percentage of ones occurring is {} and the average outcome is {}".format(percentage,average),end='\r')
time.sleep(.1)
另外要注意,使用total = total + random
不是一個好主意,您正在導入random模塊,並使用random作為變量名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.