0% found this document useful (0 votes)
13 views

STOPWATCH-APP-PYTHON

Uploaded by

vilyxu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

STOPWATCH-APP-PYTHON

Uploaded by

vilyxu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

import time

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

def save_laps_to_file(self, filename):


"""
Save laps to a file.
"""
with open(filename, "w") as file:
data = {
"laps": [self.format_time(lap) for lap in self.laps],
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
json.dump(data, file, indent=4)
print(f"Laps saved to '{filename}'.")

def load_laps_from_file(self, filename):


"""
Load laps from a file.
"""
try:
with open(filename, "r") as file:
data = json.load(file)
self.laps = [self.parse_time(lap) for lap in data["laps"]]
print(f"Laps loaded from '{filename}':")
for i, lap in enumerate(self.laps, 1):
print(f"Lap {i}: {self.format_time(lap)}")
except FileNotFoundError:
print(f"File '{filename}' not found.")
except json.JSONDecodeError:
print(f"Error decoding the JSON file '{filename}'.")

@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()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy