Python倒计时游戏需要贵丹

2024-05-21 05:13:38 发布

您现在位置: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)

我得到的输出是:

^{pr2}$

我想改变程序的输出时间:

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.

等等。在

如何转换?在


Tags: and代码import程序youtimehavecount
2条回答

将打印时间的行改为:

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

以下是全文:

^{pr2}$

以及一个示例:

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.
...

最后,这里有一个关于^{}和一个关于{a2}的引用。在

每次迭代需要睡眠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()并不精确;它只保证程序的睡眠时间不少于指定的数量。您会注意到,有时程序的暂停时间比挂钟少几秒钟。在

如果您想要更高的精度,您应该计算循环结束的最终时间,检查每次迭代的当前时间,并显示它们之间的实际差异。在

相关问题 更多 >