我正在创建一个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 :(得分: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.
...
最后,这是divmod
上的引用和str.format
上的引用。
答案 1 :(得分: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()
不准确;所有它承诺的是你的程序将睡不少于指定的数量。您会注意到,与挂钟相比,有时您的程序暂停几秒钟。
如果你想要更高的精度,你应该计算循环应该结束的最后时间,检查每次迭代的当前时间,并显示它们之间的真正差异。