Timer stops the program before it is over

45 views Asked by At

I coded a timer to last for 1 minute before the program continues, but the timer keeps on stopping at around 12 seconds and prevents the program from moving forward.

I read somewhere that the time.sleep function doesn't work if the system clock changes, and to replace it with time.monotonic, but doing that just bugged my code more. Here is my code for the timer:

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)")

I have the if statement at the end because I used the timer in two instances only: One was when I was counting down five seconds, and the other one was a timer that was a minute long. I wanted them to print different messages at the end. I do not know threading, nor do I think I need it in this specific program.

Here is the code where the countdown is called:

if require7 == "no":
    print("Okay, I'll be nice.")
    print("(Press any key to continue)")
    input()
    print("Don't tell anybody else, but I'm giving you one minute to do those pushups.")
    input()
    print("I'll count.")
    input()
    print("Ready? I'll countdown 'till I start.")
    input()
    m = 0
    s = 5
    countdown(m, s)
    # Inputs for hours, minutes, seconds on timer
    m = 1
    s = 0
    countdown(m, s)
    input()
    if (input=="yes" or "no"):
        print("Well, sorry, but you're not eligible.")
        print("You do not have qualities that we are looking for.")
        print("Goodbye.")
    else:
        print("I don't know what you just entered, but you're not eligible.")
        print("You do not have qualities that we are looking for.")
        print("Goodbye.")
1

There are 1 answers

3
TheHungryCub On

Try this:

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

Output 1:

Time remaining: 0:00:01
Go!

Alright, are you done yet? (yes/no): yes
Great! You're done.

Output 2:

Time remaining: 0:00:01
Go!

Alright, are you done yet? (yes/no): no
Please complete your task.