用Python编写一个简单的倒计时程序
发布时间:2023-12-04 16:58:06
下面是使用 Python 编写的一个简单的倒计时程序,程序可以根据用户输入的时间设置倒计时并在指定的时间内进行倒计时。
import time
def countdown(seconds):
print("倒计时开始...")
while seconds > 0:
minutes, sec = divmod(seconds, 60)
timer = '{:02d}:{:02d}'.format(minutes, sec)
print(timer, end='\r')
time.sleep(1)
seconds -= 1
print("倒计时结束!")
if __name__ == "__main__":
print("请输入需要倒计时的秒数:")
try:
seconds = int(input())
countdown(seconds)
except ValueError:
print("请输入一个有效的整数!")
使用例子:
请输入需要倒计时的秒数: 10 倒计时开始... 00:10 00:09 00:08 00:07 00:06 00:05 00:04 00:03 00:02 00:01 倒计时结束!
在上述例子中,用户输入需要倒计时的秒数为10秒。程序开始倒计时,每秒钟显示剩余的分钟和秒钟数,最终在倒计时结束时输出"倒计时结束!"。
这个简单的倒计时程序可以用来实现一些简单的倒计时功能,比如在游戏中的倒计时、考试时间的倒计时等。由于程序中使用了 time.sleep(1) 来实现每秒钟的等待,因此可能会有一点误差。如果需要更精确的倒计时,可以考虑使用更高级的时间库比如 datetime 、tkinter 等。
