How to make a timer program in Python

前端 未结 11 2484
予麋鹿
予麋鹿 2021-02-08 14:24

Here is my goal: To make a small program (text based) that will start with a greeting, print out a timer for how long it has been since the last event, and then a timer for the

11条回答
  •  半阙折子戏
    2021-02-08 15:25

    I would go with something like this:

    import time
    import sys
    
    time_start = time.time()
    seconds = 0
    minutes = 0
    
    while True:
        try:
            sys.stdout.write("\r{minutes} Minutes {seconds} Seconds".format(minutes=minutes, seconds=seconds))
            sys.stdout.flush()
            time.sleep(1)
            seconds = int(time.time() - time_start) - minutes * 60
            if seconds >= 60:
                minutes += 1
                seconds = 0
        except KeyboardInterrupt, e:
            break
    

    Here I am relying on actual time module rather than just sleep incrementer since sleep won't be exactly 1 second.

    Also, you can probably use print instead of sys.stdout.write, but you will almost certainly need sys.stdout.flush still.

    Like:

    print ("\r{minutes} Minutes {seconds} Seconds".format(minutes=minutes, seconds=seconds)),
    

    Note the trailing comma so a new line is not printed.

提交回复
热议问题