Home » 
        Python » 
        Python Programs
    
    Create a stopwatch using Python
    
    
    
    
        Stopwatch in Python: Here, we are going to implement a python program to create a stopwatch.
        
            By IncludeHelp Last updated : January 04, 2024
        
    
    
    Problem statement
    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 create a stopwatch
    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.
    
    Python program to create 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
The output of the above example is:
Press ENTER to start the stopwatch
and, press CTRL + C to stop the stopwatch
Stopwatch started...
^CStopwatch stopped...
The total time: 15.81 seconds
    By using the above code, we can create a stop watch, to practice more programs, visit – python programs.
    To understand the above program, you should have the basic knowledge of the following Python topics:
    
    Python Basic Programs »
    
    
    
    
    
    
  
    Advertisement
    
    
    
  
  
    Advertisement