Stop Watch in Python.
About the project: This program will allow you to start, stop, pause, resume, and reset a timer, displaying the elapsed time.
How to use this program:
Save the code: Save the code above as a Python file (e.g., stop_watch.py).
Run the script: Open your terminal or command prompt, navigate to the directory where you saved the file, and run:
python stop_watch.py
The program will display the current elapsed time (initially 00:00:00.000) and a menu of commands.
Enter commands like start, pause, resume, reset, or quit (or their single-letter abbreviations s, p, r, e, q) to control the stopwatch.
Project Level: Beginner
You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.
Steps: Follow these stepsStep 1: Copy below code using green 'copy' button.
Step 2: Paste the code on your chosen editor.
Step 3: Save the code with filename and .py extention.
Step 4: Run (Press F5 if using python IDLE)
# stop_watch.py
import time
import os
def clear_console():
"""Clears the console screen for a cleaner display."""
os.system('cls' if os.name == 'nt' else 'clear')
def format_time(seconds):
"""Formats seconds into HH:MM:SS.ms string."""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
remaining_seconds = seconds % 60
return f"{hours:02}:{minutes:02}:{remaining_seconds:06.3f}"
def main():
"""
Main function to run the Stop Watch.
"""
global start_time, elapsed_time_at_pause, is_running
start_time = 0.0
elapsed_time_at_pause = 0.0
is_running = False
print("--- Python Stop Watch ---")
print("Commands: start, pause, resume, reset, quit")
while True:
clear_console()
current_display_time = 0.0
if is_running:
current_display_time = elapsed_time_at_pause + (time.time() - start_time)
else:
current_display_time = elapsed_time_at_pause
print(f"Elapsed Time: {format_time(current_display_time)}")
print("\nMenu: (s)tart, (p)ause, (r)esume, (e)set, (q)uit")
# Get command without blocking the display too much
# We'll use a short sleep to allow time to read and react
time.sleep(0.1) # Small delay to prevent rapid flickering and allow input
# Check for user input non-blockingly if possible, or prompt
# For a simple CLI, a blocking input is often necessary for commands
# We'll prompt for input after showing the time
command = input("Enter command: ").strip().lower()
if command == 's' or command == 'start':
if not is_running:
start_time = time.time() - elapsed_time_at_pause # Adjust start time for resume
is_running = True
print("Stopwatch started.")
else:
print("Stopwatch is already running.")
elif command == 'p' or command == 'pause':
if is_running:
elapsed_time_at_pause = time.time() - start_time
is_running = False
print("Stopwatch paused.")
else:
print("Stopwatch is not running or already paused.")
elif command == 'r' or command == 'resume':
if not is_running and elapsed_time_at_pause > 0:
start_time = time.time() - elapsed_time_at_pause
is_running = True
print("Stopwatch resumed.")
elif is_running:
print("Stopwatch is already running.")
else:
print("Stopwatch has not been started or has been reset.")
elif command == 'e' or command == 'reset':
start_time = 0.0
elapsed_time_at_pause = 0.0
is_running = False
print("Stopwatch reset.")
elif command == 'q' or command == 'quit':
print("Exiting Stop Watch. Goodbye!")
break
else:
print("Invalid command. Please use 'start', 'pause', 'resume', 'reset', or 'quit'.")
# Add a small delay after command execution to make messages readable
time.sleep(1)
# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
main()