Reputation: 1
I am trying to create a countdown in python and I want very simple way of creating that. I watched a couple of videos but couldn't find a right solution for it.
This is the code which I am using right now.
import time
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
print('Time Over!!!!')
t = input("Enter the time in seconds: ")
countdown(int(t))
Upvotes: 0
Views: 682
Reputation: 44013
The problem is that when you sleep for 1 second, it will not be for exactly 1 second and theoretically over long enough time the errors could propagate enough such that you could conceivably be printing out an incorrect time. To correct this, your code needs to actually check in its loop how much time has actually elapsed since the start of the program running and use that to compute what the new value of t
is, and it should do this frequently so that the countdown is smooth. For example:
import time
def countdown(t):
start_time = time.time()
start_t = t
# compute accurate new t value aprroximately every .05 seconds:
while t > 0:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(.05) # finer timing
now = time.time()
elapsed_time = int(now - start_time) # truncated to seconds
t = start_t - elapsed_time
print('Time Over!!!!')
t = input("Enter the time in seconds: ")
countdown(int(t))
Upvotes: 1