0

I need the countdown to countdown while the user inputs their age

# import the time module
import time

# define the countdown func.
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('Fire in the hole!!')


# input time in seconds
t = 10

# function call
countdown(int(t))
Brian Destura
  • 11,487
  • 3
  • 18
  • 34
  • 1
    What happens when you run this, vs what do you expect? Doesn't look like you ever prompt for input when the timer ends (after the print) – OneCricketeer Jul 28 '21 at 00:47
  • @OneCricketeer I would like the timer to countdown while the user takes their time to input something in – dumbcoder Jul 28 '21 at 00:55
  • Unclear what you mean by "while the user takes their time", but sounds like you want [a separate thread](https://docs.python.org/3/library/threading.html) – OneCricketeer Jul 28 '21 at 01:00
  • @OneCricketeer,as I am fairly new to coding and only was taught simple coding, im afraid i dont understand what the seperate thread is referring to. Basically, the countdown timer runs while waiting for a user input and if the countdown ends, the user does not input something, fire in the hole will be printed out – dumbcoder Jul 28 '21 at 01:02
  • In this code, there is no way to prompt for input **and** have counter go down. If you added `input()`, it _stops the execution_ on that line. Therefore, you need a background thread doing the counting while the "main thread" uses an `input()` function – OneCricketeer Jul 28 '21 at 01:05
  • may i know how i can go about coding with the threading function? like exactly what i need to write? thanks alot for the help, really desperate with the code – dumbcoder Jul 28 '21 at 01:06
  • Well, what do you want to happen when the timer stops? If the user has not input something, do you want that do "exit"? Because, I'm not actually sure if that's possible – OneCricketeer Jul 28 '21 at 01:09
  • Several answers here that seem to do what you're asking for https://stackoverflow.com/questions/1335507/keyboard-input-with-timeout – OneCricketeer Jul 28 '21 at 01:11
  • When the timer stops, just have to print ("fire in the hole!!!") – dumbcoder Jul 28 '21 at 01:11
  • Sure, but the user "age" prompt would still be present and cannot be stopped without some input, or at least hitting the enter key, I believe – OneCricketeer Jul 28 '21 at 01:13
  • I think just hitting the enter key, it would be fine, but I really have no idea what other threads regarding to this topic are talking about, i have only gone through a few basic python codes, please help – dumbcoder Jul 28 '21 at 01:19
  • I don't know how any answer here would differ from the question I linked above. – OneCricketeer Jul 28 '21 at 01:20

0 Answers0