Reputation: 163
import time
def countdown(duration):
while duration > 0:
mins, seconds = divmod(duration, 60)
timer = '{:02d}:{:02d}'.format(mins, seconds)
print(timer, end='\r')
time.sleep(1)
duration -= 1
print("Time's up!")
countdown(int(input(": ")))
I wanted to make a timer on python and learned how to make one as well. I understood how everything worked but for some reason when I ran the code the timer didn't actually show up at all. After the cursor blinks for how long I told the timer to run, it prints the "Time's up" prompt without ever showing the timer. The duration to wait is correct though, so the timer works, it just doesn't show up.
Upvotes: 0
Views: 779
Reputation: 702
You said in your comment that you're running the code on PyCharm. That is the problem. Your code runs successfully in Linux and Windows; I just tried. However, in PyCharm, it does not show any output. This is dependent on PyCharm's way to handle carriage returns ("\r")
. More information here, it's for YouTrack but applies also to PyCharm.
Two ways to fix this:
print(timer, end='\r')
line to print(f'\r{timer}', end='')
(move carriage return to the beginning of print and remove the newline from the print)Upvotes: 3