PUBLISHED ON: AUGUST 25, 2021
Python Program to Create a Lap Timer
The lap timer requires a fixed position on the circuit from which he can trigger lap after lap with accuracy and reliability. In this tutorial, we will create a lap timer using a python program. Let us consider the input-output for a better understanding:
In the above figure, we can see that there is info to start and stop the counter and when you will enter the number it started counting the laps until you press the CTRL+C to stop the lap.
Approach
The module used in this program is the "Time" module which contains a number of time-related functions. It is included in Python's standard library and does not need to be installed. Let us now look into the approach of the program:
- To finish each lap, the user must hit ENTER.
- The timer will continue to count until CTRL+C is hit.
- The lap time is calculated by subtracting the current time from the total time at the conclusion of the preceding lap for each lap.
- The current epoch time in milliseconds is returned by the time() method of the time module.
Algorithm
As of now, we have a rough understanding of how the following program will execute. For a better understanding let us dive deep into the algorithm followed by the program.
- Import library "time"
- Define start, last, and num for the timer to start
- Use try-catch block and Input() for the enter key
- Calculate the current lap time
- Calculate the time elapsed
- Print lap number, total time and lap-time
- Update previous total time and lap number
- Stop when CTRL+C is pressed
Python Program
As mentioned in the algorithm let's try the same steps into the program to get the desired output:
import time
start=time.time()
last=start
num=1
print("Press ENTER to count lap timer.\nPress CTRL+C to stop")
try:
while True:
input()
lap=round((time.time() - last), 2)
total=round((time.time() - start), 2)
print("Lap Numer "+str(num))
print("Total Time taken: "+str(total))
print("Lap Time: "+str(lap))
print("*"*20)
last=time.time()
num+=1
# Stop
except KeyboardInterrupt:
print("Process Stopped")
Press ENTER to count lap timer.
Press CTRL+C to stop
1
Lap Numer 1
Total Time taken: 1.71
Lap Time: 1.71
********************
2
Lap Numer 2
Total Time taken: 3.36
Lap Time: 1.64
********************
3
Lap Numer 3
Total Time taken: 4.86
Lap Time: 1.5
********************
Process Stopped
Conclusion
In this tutorial, we have created a lap timer with help of a python code. We have imported the time module and uses try and catch block to create a lap timer. When the user presses Enter key the timer starts until CTRL+C is pressed by the user.