Stopwatch in Python: Here, we are going to actualize a python program to make a stopwatch.
The assignment is to make a stopwatch.
In the underneath program, the stopwatch will be begun when you press the ENTER key and halted when you press the CTRL+C key.
Rationale: To run the stopwatch (tally the time), we are composing the code in a vast circle, start time will be spared in start_time variable as you press the ENTER and when you press the CTRL + C a KeyboardInterrupt special case will produce and we will again get the time, which will be considered as end_time. Presently, to ascertain the distinction – we will just subtract the time from end_time to start_time.
To get the time in a moment or two, we are utilizing time() capacity of the time module. In this way, you have to import the time module first.
Python code for a stopwatch:
# Python code for a stopwatch
# importing the time module
import time
print("Press ENTER to start the stopwatch")
print("and, press CTRL + C to stop the stopwatch")
# infinite loop
while True:
try:
input() #For ENTER
start_time = time.time()
print("Stopwatch started...")
except KeyboardInterrupt:
print("Stopwatch stopped...")
end_time = time.time()
print("The total time:", round(end_time - start_time, 2),"seconds")
break # breaking the loop
Output:
Press ENTER to start the stopwatch
and, press CTRL + C to stop the stopwatch
Stopwatch started...
^CStopwatch stopped...
The total time: 15.81 seconds