创建一个倒计时计时器,给定用户以mm:ss格式输入的分秒数



系统会提示用户以mm:ss格式输入分钟和秒数。则计时器必须一次倒计时一秒。每秒钟,必须以mm:ss格式打印剩余时间。我很难弄清楚如何用这种格式分隔时间。这就是我到目前为止所拥有的。这个问题很可能就在";而"是";陈述

import time
x=input("Countdown Time Limit: ")
def countdown(time_sec):
minutes = int(time_sec[:0])
seconds = int(time_sec[0:])
temp = 0
while True:
if seconds == -1:
seconds = 59
minutes -= 1
if (seconds > 9):
print('r',str(temp) + str(minutes) + ":" + str(seconds),end='')
else:
print('r',str(temp) + str(minutes) + ":" + str(temp) + str(seconds),end='')
time.sleep(1)
seconds -= 1
if(minutes==0 and seconds==-1):
break
print('n',"STOP")
countdown(x)

就像@Alex说的用:分割输入。然后使用python格式{:02}为数字添加0。您也可以只使用秒进行倒计时:

import time
x=input("Countdown Time Limit: ")
def countdown(time_sec):
tst = time_sec.split(':')
minutes = int(tst[0])
seconds = int(tst[1]) + 60 * minutes
# no need for break
while seconds > 0:
# seconds (0-59) is just time in seconds modulo 60
# and minutes time in second divided by 60 (here remove the seconds to prevent rounding)
s = seconds % 60
m = int((seconds - s) / 60)
# format 2 digits with leading 0
print("{:02}:{:02}".format(m,s))
time.sleep(1)
# easier to not have to worry about the 59 -> 0 test
seconds -= 1

print('n',"STOP")
countdown(x)

最新更新