Q:

Create a stopwatch using Python

belongs to collection: Python basic programs

0

The task is to create a stopwatch.

In the below program, the stopwatch will be started when you press the ENTER key and stopped when you press the CTRL+C key.

Logic: To run the stopwatch (count the time), we are writing the code in an infinite loop, start time will be saved in start_time variable as you press the ENTER and when you press the CTRL + C a KeyboardInterrupt exception will generate and we will again get the time, which will be considered as end_time. Now, to calculate the difference – we will simply subtract the time from end_time to start_time.

To get the time in seconds, we are using time() function of the time module. So, you need to import the time module first.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python basic programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to find the maximum multiple from g... >>
<< Python | Convert the decimal number to binary with...