I'm currently making a stopwatch function, where the user has to input 1 to start and 2 to stop the stopwatch. I'm wondering how to implement the stop function when the while loop is going on as whatever I tried didn't work.
This is the stopwatch code I'm working on:
second = 0
minute = 0
hour = 0
millisecond = 0
start = input("Press 1 to start and 2 to stop: ")
while True:
if start == "2":
break
else:
print("%02d : %02d : %02d "%(hour, minute, second,))
time.sleep(1)
second += 1
if second == 60:
minute += 1
second -= 60
if minute == 60:
hour += 1
minute -= 60
ctrl+cto stop itinputblocks until the user types something, the only way to do this is to use threading. You could create a thread to print your countdown, have the main thread block on aninputcall , and signal the thread to stop.python threading. It's not really very hard. The only trick is you can't force the thread to exit; you need to set a global flag that the thread checks on its own.