gpt4 book ai didi

Python倒计时小游戏需要指导

转载 作者:太空宇宙 更新时间:2023-11-04 09:06:17 25 4
gpt4 key购买 nike

我正在创建一个 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.

等等。

如何转换?

最佳答案

将打印时间的行更改为:

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 .

关于Python倒计时小游戏需要指导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20503246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com