我编写了一个计时器,使其在程序继续之前持续 1 分钟,但计时器在 12 秒左右停止并阻止程序继续前进。
我在某处读到,如果系统时钟发生变化,
time.sleep
函数将不起作用,并将其替换为time.monotonic
,但这样做只会让我的代码出现更多错误。
这是我的计时器代码:
import time
import datetime
def countdown(m, s):
total_seconds = m * 60 + s
while total_seconds > 0:
timer = datetime.timedelta(seconds = total_seconds)
print(timer, end="\r")
time.sleep(1)
total_seconds -= 1
if s == 5:
print("Go!")
print("")
else:
print("Alright, are you done yet? (yes/no)")
我在最后有
if
声明,因为我只在两个实例中使用了计时器:一个是当我倒计时五秒时,另一个是一分钟长的计时器。我希望他们最后打印不同的消息。我不了解线程,我也不认为在这个特定的程序中需要它。
试试这个:
import time
import datetime
def countdown(m, s):
try:
total_seconds = m * 60 + s
while total_seconds > 0:
timer = datetime.timedelta(seconds=total_seconds)
print(f"Time remaining: {timer}", end="\r")
time.sleep(1)
total_seconds -= 1
print("\nGo!")
print("")
response = input("Alright, are you done yet? (yes/no): ").strip().lower()
if response == "yes":
print("Great! You're done.")
else:
print("Please complete your task.")
except ValueError:
print("Invalid input. Please enter valid minutes and seconds.")
# Example usage:
countdown(0, 10) # Countdown from 0 minutes and 10 seconds
输出1:
Time remaining: 0:00:01
Go!
Alright, are you done yet? (yes/no): yes
Great! You're done.
输出2:
Time remaining: 0:00:01
Go!
Alright, are you done yet? (yes/no): no
Please complete your task.