STOPWATCH-APP-PYTHON
STOPWATCH-APP-PYTHON
import json
from datetime import datetime
class Stopwatch:
"""
A class to represent a stopwatch.
"""
def __init__(self):
self.start_time = None
self.elapsed_time = 0
self.running = False
self.laps = []
def start(self):
"""
Start the stopwatch.
"""
if not self.running:
self.start_time = time.time() - self.elapsed_time
self.running = True
else:
print("Stopwatch is already running.")
def stop(self):
"""
Stop the stopwatch.
"""
if self.running:
self.elapsed_time = time.time() - self.start_time
self.running = False
else:
print("Stopwatch is not running.")
def reset(self):
"""
Reset the stopwatch.
"""
self.start_time = None
self.elapsed_time = 0
self.running = False
self.laps = []
def lap(self):
"""
Record a lap time.
"""
if self.running:
current_time = time.time() - self.start_time
lap_time = current_time - (sum(self.laps) if self.laps else 0)
self.laps.append(lap_time)
print(f"Lap {len(self.laps)}: {self.format_time(lap_time)}")
else:
print("Stopwatch is not running. Start it first to record laps.")
def get_time(self):
"""
Get the current elapsed time.
"""
if self.running:
return time.time() - self.start_time
return self.elapsed_time
@staticmethod
def format_time(seconds):
"""
Format time in seconds to a string (HH:MM:SS.mmm).
"""
milliseconds = int((seconds % 1) * 1000)
minutes, seconds = divmod(int(seconds), 60)
hours, minutes = divmod(minutes, 60)
return f"{hours:02}:{minutes:02}:{seconds:02}.{milliseconds:03}"
@staticmethod
def parse_time(time_str):
"""
Parse time string back to seconds.
"""
hours, minutes, seconds = time_str.split(":")
seconds, milliseconds = seconds.split(".")
return int(hours) * 3600 + int(minutes) * 60 + int(seconds) +
int(milliseconds) / 1000
def __str__(self):
"""
String representation of the stopwatch state.
"""
status = "Running" if self.running else "Stopped"
elapsed = self.format_time(self.get_time())
laps = "\n".join([f"Lap {i + 1}: {self.format_time(lap)}" for i, lap in
enumerate(self.laps)])
return f"Stopwatch [{status}] | Elapsed Time: {elapsed}\n{laps}"
def display_menu():
"""
Display the menu of options.
"""
print("\n--- Stopwatch Menu ---")
print("1. Start Stopwatch")
print("2. Stop Stopwatch")
print("3. Reset Stopwatch")
print("4. Record Lap")
print("5. View Elapsed Time")
print("6. View All Laps")
print("7. Save Laps to File")
print("8. Load Laps from File")
print("9. Exit")
def main():
"""
Main function to run the stopwatch app.
"""
stopwatch = Stopwatch()
print("Welcome to the Stopwatch App!")
while True:
display_menu()
choice = input("Choose an option: ")
if choice == "1":
stopwatch.start()
print("Stopwatch started.")
elif choice == "2":
stopwatch.stop()
print("Stopwatch stopped.")
elif choice == "3":
stopwatch.reset()
print("Stopwatch reset.")
elif choice == "4":
stopwatch.lap()
elif choice == "5":
elapsed_time = stopwatch.get_time()
print(f"Elapsed Time: {stopwatch.format_time(elapsed_time)}")
elif choice == "6":
print("\n--- All Laps ---")
if stopwatch.laps:
for i, lap in enumerate(stopwatch.laps, 1):
print(f"Lap {i}: {stopwatch.format_time(lap)}")
else:
print("No laps recorded.")
elif choice == "7":
filename = input("Enter filename to save laps: ")
stopwatch.save_laps_to_file(filename)
elif choice == "8":
filename = input("Enter filename to load laps: ")
stopwatch.load_laps_from_file(filename)
elif choice == "9":
print("Exiting Stopwatch App. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()