Python Program to Create a Lap Timer


When it is required to create a lap timer using Python, the ‘time’ method is used. The number of laps is predefined, and a try catch block is defined, to start the lap timer.

Below is a demonstration of the same −

Example

 Live Demo

import time

start_time=time.time()
end_time=start_time
lap_num=1

print("Click on ENTER to count laps.\nPress CTRL+C to stop")

try:
   while True:

      input()
      time_laps=round((time.time() - end_time), 2)

      tot_time=round((time.time() - start_time), 2)

      print("Lap No. "+str(lap_num))
      print("Total Time: "+str(tot_time))
      print("Lap Time: "+str(time_laps))

      print("*"*20)

      end_time=time.time()
      lap_num+=1

except KeyboardInterrupt:
   print("Exit!")

Output

Click on ENTER to count laps.
Press CTRL+C to stop

Lap No. 1
To
tal Time: 1.77
Lap Time: 1.77
********************

Lap No. 2
Total Time: 3.52
Lap Time: 1.75
********************
Exit!

Explanation

  • The required packages are imported.

  • The start time, end time and number of laps are defined.

  • The timer starts by clicking on ‘Enter’.

  • In the try catch block, the difference between current time and end time is determined.

  • Again, the difference between current time and start time is determined.

  • This gives the number of laps, total time, and lap time.

  • This is displayed as output on the console.

  • In the ‘except’ block, the ‘Exit’ is defined.

Updated on: 15-Apr-2021

414 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements