2013-12-10 351 views
1

我創建一個python程序倒計時,但我與它有麻煩。Python的倒計時遊戲需要指導做好

這裏是我的代碼:

import time 

def countdown(count): 
    while (count >= 0): 
     print ("Time remaining: "+ str(count) + " seconds") 
     count -= 1 
     time.sleep(1) 

countdown(120) 
print("Times up!") 
time.sleep(3) 

我得到的輸出是:

Time remaining: 120 seconds 
Time remaining: 119 seconds 
Time remaining: 118 seconds 
Time remaining: 117 seconds 
Time remaining: 116 seconds 

我想改變計劃,以分和秒來使程序輸出:

You have 2 minutes and 2 seconds remaining. 
You have 2 minutes and 1 seconds remaining. 
You have 2 minutes and 0 seconds remaining. 
You have 1 minutes and 59 seconds remaining. 

等。

請幫我把它轉換。

+0

當您按原樣運行該程序時,您能告訴我們您的輸出是什麼嗎? – jwarner112

+0

@ jwarner112:我編輯了我的問題以包含我的輸出。請提前看看並感謝。 – user3088253

+0

@ user3088253看看了'divmod'內置函數 –

回答

1

你睡1秒每次迭代,所以count是剩餘的秒數。

分鐘數爲count/60,剩餘秒數爲count % 60(模數)。所以,你可以寫類似

mins = count/60 
secs = count % 60 

print "Time remaining is %d minutes %d seconds" % (mins, secs) 

您可以在一個操作中mins, secs = divmod(count, 60)同時計算分和秒。

請注意:sleep()不準確;它承諾的一切就是你的程序不會少於指定的數量。您會注意到,與掛鐘相比,您的程序的暫停有時幾秒鐘。

如果你想更精確,您應該計算循環何時結束的最後時間,檢查每個迭代的當前時間,並顯示它們之間的真正區別。

4

更改,打印時間的行:

print("You have {} minutes and {} seconds remaining.".format(*divmod(count, 60))) 

以下是完整的腳本:

import time 

def countdown(count): 
    while (count >= 0): 
     print("You have {} minutes and {} seconds remaining.".format(*divmod(count, 60))) 
     count -= 1 
     time.sleep(1) 

print("Welcome. This program will put your computer to sleep in 5 minutes.") 
print("To abort shutdown, please close the program.\n") 

countdown(120) 
print("Times up!") 
time.sleep(3) 

和樣品運行:

Welcome. This program will put your computer to sleep in 5 minutes. 
To abort shutdown, please close the program. 

You have 2 minutes and 0 seconds remaining. 
You have 1 minutes and 59 seconds remaining. 
You have 1 minutes and 58 seconds remaining. 
You have 1 minutes and 57 seconds remaining. 
You have 1 minutes and 56 seconds remaining. 
You have 1 minutes and 55 seconds remaining. 
... 

最後,這裏是divmodstr.format上的一個參考。