简体   繁体   中英

Countdown timer in python does not actually display anything

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.

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:

  • change your 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)
  • Enable "Emulate terminal in output console" in Run/Debug configuration (Edit configurations...) in your PyCharm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM