Create a stopwatch using Python

Stopwatch in Python: Here, we are going to implement a python program to create a stopwatch.
Submitted by IncludeHelp, on August 09, 2019

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.

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:
        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


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.

Python Basic Programs »



Comments and Discussions!





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.