From 7120a0aba7729c2185aca646ff8d7f550844353d Mon Sep 17 00:00:00 2001 From: Daniele Fiocca Date: Mon, 2 Jun 2025 17:57:38 +0200 Subject: [PATCH 1/3] My solution for final project --- .gitignore | 1 + .../solution/danieleFiocca/index.py | 254 ++++++++++++++++++ 2 files changed, 255 insertions(+) create mode 100644 projects/final-project/solution/danieleFiocca/index.py diff --git a/.gitignore b/.gitignore index a5b9cff..f8b98e2 100644 --- a/.gitignore +++ b/.gitignore @@ -371,3 +371,4 @@ Cargo.lock # End of https://www.toptal.com/developers/gitignore/api/node,go,java,intellij,visualstudiocode,haskell,erlang,elixir,rust /.vs/ProjectSettings.json /.vs/slnx.sqlite +.DS_Store diff --git a/projects/final-project/solution/danieleFiocca/index.py b/projects/final-project/solution/danieleFiocca/index.py new file mode 100644 index 0000000..a3d52da --- /dev/null +++ b/projects/final-project/solution/danieleFiocca/index.py @@ -0,0 +1,254 @@ +""" With this tool you can display the date and time in different formats, display the same time in different time zones and create a timer """ + +from datetime import datetime +from zoneinfo import ZoneInfo +import time +import threading + +def currentTime(): + now = datetime.now() + date_time = now.strftime('%d/%b/%Y - %H:%M:%S') + + # Day off the week + day_of_week = now.strftime('%A') + + # Day of year + day_of_year = now.strftime('%j') + + # Week number + week_number = now.strftime('%W') + + print("--- DATA AND TIME INFORMATION ---") + print(f"\nDate and time: {date_time}") + print(f"Day of the week: {day_of_week}") + print(f"Day of the year: {day_of_year}") + print(f"Week number: {week_number}") + + + + +def time_zone(): + time_zones = input("Insert the time zone in format (Zone/Country): ") + try: + + fuse = datetime.now(ZoneInfo(time_zones)) + print(fuse.strftime('%d/%b/%Y - %H:%M:%S')) + except Exception as e: + print(f"Error: {e}") + + +def timer(): + t = input("enter time in seconds: ") + try: + t = int(t) + except ValueError: + print("Invalid input. Please enter a number") + return + + # Control Events of threading + pause = threading.Event() + stop = threading.Event() + reset = threading.Event() + + timer_data = {'time': t, 'format': 1} + + + print("Choose format time:") + print("1. Complete (DD:HH:MM:SS)") + print("2. Hour:Minute:Seconds") + print("3. Minute:Seconds") + print("4. Seconds") + + try: + select = int(input("Format select: ")) + if select not in [1, 2, 3, 4]: + print("Invalid selection") + select = 1 + except ValueError: + print("Invalid input") + select = 1 + + timer_data["format"] = select + + def countdown(): + while not stop.is_set(): + current_time = timer_data['time'] + + if current_time < 0: + print("\nTime's up!") + break + + if pause.is_set(): + time.sleep(0.1) + continue + + if reset.is_set(): + reset.clear() + continue + + mins, secs = divmod(current_time, 60) + hours, mins = divmod(mins, 60) + days, hours = divmod(hours, 24) + + if timer_data['format'] == 1: + timer_display = '{:02d}:{:02d}:{:02d}:{:02d}'.format(days, hours, mins, secs) + elif timer_data['format'] == 2: + total_hours = days * 24 + hours + timer_display = '{:02d}:{:02d}:{:02d}'.format(total_hours, mins, secs) + elif timer_data['format'] == 3: + total_mins = (days * 24 * 60) + (hours * 60) + mins + timer_display = '{:02d}:{:02d}'.format(total_mins, secs) + elif timer_data['format'] == 4: + total_secs = current_time + timer_display = '{:03d}'.format(total_secs) + + print(f"\r{timer_display} ", end='', flush=True) + time.sleep(1) + timer_data['time'] -= 1 + + timer_thread = threading.Thread(target=countdown) + timer_thread.daemon = True + timer_thread.start() + + try: + while True: + print("\nCommand: pause, start, reset, stop") + command = input(">>> ").strip().lower() + if command == "pause": + pause.set() + print("Timer paused") + elif command == "start" or command == "resume": + pause.clear() + print("Timer resumed") + elif command == "reset": + timer() + elif command == "stop": + stop.set() + print("Timer stopped") + break + else: + print("Invalid command") + except KeyboardInterrupt: + stop.set() + print("\nTimer interrupted") + timer_thread.join(timeout=2) + print("Timer finished") + + +def world_clock(): + clocks = [] # List of saved Time zone + + timezones_list = { + '1': ('Europe/Rome', 'Rome, Italy'), + '2': ('Europe/London', 'London, United Kingdom'), + '3': ('America/New_York', 'New York, USA'), + '4': ('America/Los_Angeles', 'Los Angeles, USA'), + '5': ('Asia/Tokyo', 'Tokyo, Japan'), + '6': ('Asia/Shanghai', 'Shanghai, Cina'), + '7': ('Australia/Sydney', 'Sydney, Australia'), + '8': ('Europe/Paris', 'Parigi, France'), + '9': ('Asia/Dubai', 'Dubai, UAE'), + '10': ('America/Sao_Paulo', 'San Paolo, Brazil') + } + + def display_clocks(): + if not clocks: + print("No clocks are append") + return + + print("\n--- WORLD CLOCKS ---") + + current_time = datetime.now() + + for i, (timezone, city_name) in enumerate(clocks, 1): + + tz_time = current_time.astimezone(ZoneInfo(timezone)) + time_str = tz_time.strftime('%H:%M:%S') + date_str = tz_time.strftime('%d/%m/%Y') + day_str = tz_time.strftime('%A') + + local_time = current_time.astimezone() + time_diff = (tz_time.utcoffset() - local_time.utcoffset()).total_seconds() / 3600 + diff_str = f"(UTC{time_diff:+.0f})" if time_diff != 0 else "(UTC)" + + print(f"{i:2d}. {city_name:<25} | {time_str} | {day_str:<5} | {date_str} | {diff_str}") + + + print("\n") + + def add_timezone(): + print("\nADD NEW TIMEZONE") + print("Choose from the list of available timezone\n") + + for key, (tz,name) in timezones_list.items(): + print(f"{key:2s}. {name}") + + selection = input("\nChoose (1-10): ").strip() + if selection in timezones_list: + timezone, city_name = timezones_list[selection] + clocks.append((timezone, city_name)) + else: + print("Invalid Selection.") + + def remove_timezone(): + if not clocks: + print("No clocks to remove") + return + + display_clocks() + try: + index = int(input(f"\nClock to remove? (1-{len(clocks)}): ")) -1 + if 0 <= index < len(clocks): + removed = clocks.pop(index) + print(f"Removed: {removed[1]}") + else: + print("Invalid Select") + except ValueError: + print("Insert a valid number") + + while True: + print("\nWORLD CLOCKS") + print("1. Show all clocks") + print("2. Add new clock") + print("3. Remove clock") + print("4. Back to main menù") + + choice = input("\nWhat do you do? ").strip() + + if choice == '1': + display_clocks() + elif choice =="2": + add_timezone() + elif choice == "3": + remove_timezone() + elif choice == "4": + break + else: + print("Invalid Selection.") + + +def main(): + + while True: + print("\n==== Simple Time Display ====") + print("1. For time visualization") + print("2. For visualize the time in other time zone") + print("3. For set a countdown timer") + print("4. For show world clock") + print("0. For exit.") + select = int(input("Select mode: ")) + if select == 1: + currentTime() + elif select == 2: + time_zone() + elif select == 3: + timer() + elif select == 4: + world_clock() + elif select == 0: + print("Thank's for using. See you soon") + break + + +if __name__ == "__main__": + main() \ No newline at end of file From 94fb619c93bc0623a17a013e27dac60e58bddd2d Mon Sep 17 00:00:00 2001 From: Daniele Fiocca Date: Sun, 22 Jun 2025 16:37:55 +0200 Subject: [PATCH 2/3] Last solution for final project: Added module division and "refinement" of functions according to latest instructions --- .../solution/danieleFiocca/index.py | 254 ------------------ .../simple_time_display/__init__.py | 0 .../simple_time_display/countdown_display.py | 111 ++++++++ .../simple_time_display/current_time.py | 25 ++ .../simple_time_display/index.py | 4 + .../danieleFiocca/simple_time_display/main.py | 43 +++ .../timezone_conversion.py | 48 ++++ .../simple_time_display/world_clock.py | 114 ++++++++ 8 files changed, 345 insertions(+), 254 deletions(-) delete mode 100644 projects/final-project/solution/danieleFiocca/index.py create mode 100644 projects/final-project/solution/danieleFiocca/simple_time_display/__init__.py create mode 100644 projects/final-project/solution/danieleFiocca/simple_time_display/countdown_display.py create mode 100644 projects/final-project/solution/danieleFiocca/simple_time_display/current_time.py create mode 100644 projects/final-project/solution/danieleFiocca/simple_time_display/index.py create mode 100644 projects/final-project/solution/danieleFiocca/simple_time_display/main.py create mode 100644 projects/final-project/solution/danieleFiocca/simple_time_display/timezone_conversion.py create mode 100644 projects/final-project/solution/danieleFiocca/simple_time_display/world_clock.py diff --git a/projects/final-project/solution/danieleFiocca/index.py b/projects/final-project/solution/danieleFiocca/index.py deleted file mode 100644 index a3d52da..0000000 --- a/projects/final-project/solution/danieleFiocca/index.py +++ /dev/null @@ -1,254 +0,0 @@ -""" With this tool you can display the date and time in different formats, display the same time in different time zones and create a timer """ - -from datetime import datetime -from zoneinfo import ZoneInfo -import time -import threading - -def currentTime(): - now = datetime.now() - date_time = now.strftime('%d/%b/%Y - %H:%M:%S') - - # Day off the week - day_of_week = now.strftime('%A') - - # Day of year - day_of_year = now.strftime('%j') - - # Week number - week_number = now.strftime('%W') - - print("--- DATA AND TIME INFORMATION ---") - print(f"\nDate and time: {date_time}") - print(f"Day of the week: {day_of_week}") - print(f"Day of the year: {day_of_year}") - print(f"Week number: {week_number}") - - - - -def time_zone(): - time_zones = input("Insert the time zone in format (Zone/Country): ") - try: - - fuse = datetime.now(ZoneInfo(time_zones)) - print(fuse.strftime('%d/%b/%Y - %H:%M:%S')) - except Exception as e: - print(f"Error: {e}") - - -def timer(): - t = input("enter time in seconds: ") - try: - t = int(t) - except ValueError: - print("Invalid input. Please enter a number") - return - - # Control Events of threading - pause = threading.Event() - stop = threading.Event() - reset = threading.Event() - - timer_data = {'time': t, 'format': 1} - - - print("Choose format time:") - print("1. Complete (DD:HH:MM:SS)") - print("2. Hour:Minute:Seconds") - print("3. Minute:Seconds") - print("4. Seconds") - - try: - select = int(input("Format select: ")) - if select not in [1, 2, 3, 4]: - print("Invalid selection") - select = 1 - except ValueError: - print("Invalid input") - select = 1 - - timer_data["format"] = select - - def countdown(): - while not stop.is_set(): - current_time = timer_data['time'] - - if current_time < 0: - print("\nTime's up!") - break - - if pause.is_set(): - time.sleep(0.1) - continue - - if reset.is_set(): - reset.clear() - continue - - mins, secs = divmod(current_time, 60) - hours, mins = divmod(mins, 60) - days, hours = divmod(hours, 24) - - if timer_data['format'] == 1: - timer_display = '{:02d}:{:02d}:{:02d}:{:02d}'.format(days, hours, mins, secs) - elif timer_data['format'] == 2: - total_hours = days * 24 + hours - timer_display = '{:02d}:{:02d}:{:02d}'.format(total_hours, mins, secs) - elif timer_data['format'] == 3: - total_mins = (days * 24 * 60) + (hours * 60) + mins - timer_display = '{:02d}:{:02d}'.format(total_mins, secs) - elif timer_data['format'] == 4: - total_secs = current_time - timer_display = '{:03d}'.format(total_secs) - - print(f"\r{timer_display} ", end='', flush=True) - time.sleep(1) - timer_data['time'] -= 1 - - timer_thread = threading.Thread(target=countdown) - timer_thread.daemon = True - timer_thread.start() - - try: - while True: - print("\nCommand: pause, start, reset, stop") - command = input(">>> ").strip().lower() - if command == "pause": - pause.set() - print("Timer paused") - elif command == "start" or command == "resume": - pause.clear() - print("Timer resumed") - elif command == "reset": - timer() - elif command == "stop": - stop.set() - print("Timer stopped") - break - else: - print("Invalid command") - except KeyboardInterrupt: - stop.set() - print("\nTimer interrupted") - timer_thread.join(timeout=2) - print("Timer finished") - - -def world_clock(): - clocks = [] # List of saved Time zone - - timezones_list = { - '1': ('Europe/Rome', 'Rome, Italy'), - '2': ('Europe/London', 'London, United Kingdom'), - '3': ('America/New_York', 'New York, USA'), - '4': ('America/Los_Angeles', 'Los Angeles, USA'), - '5': ('Asia/Tokyo', 'Tokyo, Japan'), - '6': ('Asia/Shanghai', 'Shanghai, Cina'), - '7': ('Australia/Sydney', 'Sydney, Australia'), - '8': ('Europe/Paris', 'Parigi, France'), - '9': ('Asia/Dubai', 'Dubai, UAE'), - '10': ('America/Sao_Paulo', 'San Paolo, Brazil') - } - - def display_clocks(): - if not clocks: - print("No clocks are append") - return - - print("\n--- WORLD CLOCKS ---") - - current_time = datetime.now() - - for i, (timezone, city_name) in enumerate(clocks, 1): - - tz_time = current_time.astimezone(ZoneInfo(timezone)) - time_str = tz_time.strftime('%H:%M:%S') - date_str = tz_time.strftime('%d/%m/%Y') - day_str = tz_time.strftime('%A') - - local_time = current_time.astimezone() - time_diff = (tz_time.utcoffset() - local_time.utcoffset()).total_seconds() / 3600 - diff_str = f"(UTC{time_diff:+.0f})" if time_diff != 0 else "(UTC)" - - print(f"{i:2d}. {city_name:<25} | {time_str} | {day_str:<5} | {date_str} | {diff_str}") - - - print("\n") - - def add_timezone(): - print("\nADD NEW TIMEZONE") - print("Choose from the list of available timezone\n") - - for key, (tz,name) in timezones_list.items(): - print(f"{key:2s}. {name}") - - selection = input("\nChoose (1-10): ").strip() - if selection in timezones_list: - timezone, city_name = timezones_list[selection] - clocks.append((timezone, city_name)) - else: - print("Invalid Selection.") - - def remove_timezone(): - if not clocks: - print("No clocks to remove") - return - - display_clocks() - try: - index = int(input(f"\nClock to remove? (1-{len(clocks)}): ")) -1 - if 0 <= index < len(clocks): - removed = clocks.pop(index) - print(f"Removed: {removed[1]}") - else: - print("Invalid Select") - except ValueError: - print("Insert a valid number") - - while True: - print("\nWORLD CLOCKS") - print("1. Show all clocks") - print("2. Add new clock") - print("3. Remove clock") - print("4. Back to main menù") - - choice = input("\nWhat do you do? ").strip() - - if choice == '1': - display_clocks() - elif choice =="2": - add_timezone() - elif choice == "3": - remove_timezone() - elif choice == "4": - break - else: - print("Invalid Selection.") - - -def main(): - - while True: - print("\n==== Simple Time Display ====") - print("1. For time visualization") - print("2. For visualize the time in other time zone") - print("3. For set a countdown timer") - print("4. For show world clock") - print("0. For exit.") - select = int(input("Select mode: ")) - if select == 1: - currentTime() - elif select == 2: - time_zone() - elif select == 3: - timer() - elif select == 4: - world_clock() - elif select == 0: - print("Thank's for using. See you soon") - break - - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/projects/final-project/solution/danieleFiocca/simple_time_display/__init__.py b/projects/final-project/solution/danieleFiocca/simple_time_display/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/projects/final-project/solution/danieleFiocca/simple_time_display/countdown_display.py b/projects/final-project/solution/danieleFiocca/simple_time_display/countdown_display.py new file mode 100644 index 0000000..73d2327 --- /dev/null +++ b/projects/final-project/solution/danieleFiocca/simple_time_display/countdown_display.py @@ -0,0 +1,111 @@ +import time +import threading + + +def set_timer(): + """Setting the timer in seconds""" + timer = int(input("Enter a time in seconds: ")) + while True: + if timer > 0: + return timer + else: + print("Value of timer must be greater than 0.") + + +def get_format_input(): + """Setting the format for display countdown""" + print("\nChoose time format:") + print("1. Complete (DD:HH:MM:SS)") + print("2. Hour:Minute:Seconds") + print("3. Minute:Seconds") + print("4. Seconds") + + while True: + format_select = int(input("\nEnter a time format: ")) + if format_select in [1, 2, 3, 4]: + return format_select + else: + print("Selection must be 1 to 4.") + + +def format_display_timer(seconds, format_selected): + """Formatting the display countdown""" + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + if format_selected == 1: + return '{:02d}:{:02d}:{:02d}:{:02d}'.format(days, hours, minutes, seconds) + if format_selected == 2: + total_hours = days * 24 + hours + return '{:02d}:{:02d}:{:02d}'.format(total_hours, minutes, seconds) + if format_selected == 3: + total_minutes = (days * 24 * 60) + (hours * 60) + minutes + return '{:02d}:{:02d}'.format(total_minutes, seconds) + if format_selected == 4: + return '{:04d}'.format(seconds) + + +def countdown_logic(initial_seconds, format_selected, pause_event, stop_event, reset_event): + """Countdown logic""" + seconds = initial_seconds + while seconds >= 0: + if stop_event.is_set(): + return + + if reset_event.is_set(): + seconds = initial_seconds + reset_event.clear() + print(f"\nReset to: {format_display_timer(seconds, format_selected)}") + + if not pause_event.is_set(): + print(f"\r{format_display_timer(seconds, format_selected)} ", end="", flush=True) + time.sleep(1) + seconds -= 1 + else: + time.sleep(0.1) # While paused + if not stop_event.is_set(): + print("\nTimer finished.") + + +def handle_commands(pause, stop, reset): + """Logic for threading commands""" + print("Command available: start, pause, stop, reset") + + while True: + command = input("\n>>>").strip().lower() + if command == "start": + pause.clear() + print("Timer started") + elif command == "pause": + pause.set() + print("Timer paused") + elif command == "reset": + reset.set() + print("Timer reset") + elif command == "stop": + stop.set() + print("Timer stopped") + break + else: + print("Command not available") + + +def start_timer(): + """Function to start the timer """ + seconds = set_timer() + format_selected = get_format_input() + + pause = threading.Event() + stop = threading.Event() + reset = threading.Event() + + timer_thread = threading.Thread(target=countdown_logic, args=(seconds, format_selected, pause, stop, reset)) + timer_thread.start() + + handle_commands(pause, stop, reset) + + timer_thread.join() + print("\nTimer finished.") + + + diff --git a/projects/final-project/solution/danieleFiocca/simple_time_display/current_time.py b/projects/final-project/solution/danieleFiocca/simple_time_display/current_time.py new file mode 100644 index 0000000..6b6f3c7 --- /dev/null +++ b/projects/final-project/solution/danieleFiocca/simple_time_display/current_time.py @@ -0,0 +1,25 @@ +from datetime import datetime + + +def current_date_time(): + return datetime.now().strftime('%d/%m/%Y %H:%M:%S') + + +def day_of_the_week(): + return datetime.now().strftime('%A') + + +def day_of_the_year(): + return datetime.now().strftime('%j') + + +def week_number(): + return datetime.now().strftime('%W') + + +def show_date_time(): + print("--- DATA AND TIME INFORMATION ---") + print(f"\nDate and time: {current_date_time()}") + print(f"Day of the week: {day_of_the_week()}") + print(f"Day of the year: {day_of_the_year()}") + print(f"Week number: {week_number()}\n") diff --git a/projects/final-project/solution/danieleFiocca/simple_time_display/index.py b/projects/final-project/solution/danieleFiocca/simple_time_display/index.py new file mode 100644 index 0000000..b7377c5 --- /dev/null +++ b/projects/final-project/solution/danieleFiocca/simple_time_display/index.py @@ -0,0 +1,4 @@ +from main import main + +if __name__ == '__main__': + main() diff --git a/projects/final-project/solution/danieleFiocca/simple_time_display/main.py b/projects/final-project/solution/danieleFiocca/simple_time_display/main.py new file mode 100644 index 0000000..d16c62b --- /dev/null +++ b/projects/final-project/solution/danieleFiocca/simple_time_display/main.py @@ -0,0 +1,43 @@ +def show_menu(): + """Function to display menu""" + print("--- Simple Time Display ---") + print("1. Display time with additional date information") + print("2. Time zone conversion") + print("3. Set a countdown") + print("4. World clock collection") + print("5. Exit") + + +def choose_menu(): + """function to select in menu""" + choice = input("Select an option: ").strip() + return choice + + +def elaborate_choice(choice): + """function to elaborate choice""" + while choice in ["1", "2", "3", "4", "5"]: + if choice == "1": + from current_time import show_date_time + show_date_time() + elif choice == "2": + from timezone_conversion import show_timezone_converted + show_timezone_converted() + elif choice == "3": + from countdown_display import start_timer + start_timer() + elif choice == "4": + from world_clock import world_clock + world_clock() + elif choice == "5": + print("Thank you for using this program!") + exit() + else: + print("Invalid selection.") + +def main(): + """Main function""" + while True: + show_menu() + choice = choose_menu() + elaborate_choice(choice) diff --git a/projects/final-project/solution/danieleFiocca/simple_time_display/timezone_conversion.py b/projects/final-project/solution/danieleFiocca/simple_time_display/timezone_conversion.py new file mode 100644 index 0000000..938b3ef --- /dev/null +++ b/projects/final-project/solution/danieleFiocca/simple_time_display/timezone_conversion.py @@ -0,0 +1,48 @@ +from datetime import datetime +from zoneinfo import ZoneInfo + + +def get_timezones_available(): + """Function for retrieving available timezones.""" + return { + '1': ('Europe/Rome', 'Rome, Italy'), + '2': ('Europe/London', 'London, United Kingdom'), + '3': ('America/New_York', 'New York, USA'), + '4': ('America/Los_Angeles', 'Los Angeles, USA'), + '5': ('Asia/Tokyo', 'Tokyo, Japan'), + '6': ('Asia/Shanghai', 'Shanghai, China'), + '7': ('Australia/Sydney', 'Sydney, Australia'), + '8': ('Europe/Paris', 'Paris, France'), + '9': ('Asia/Dubai', 'Dubai, UAE'), + '10': ('America/Sao_Paulo', 'São Paulo, Brazil') + } + + +def show_timezones(): + """function to display available timezones.""" + time_zones = get_timezones_available() + for timezone, (tz, names) in time_zones.items(): + print(f"{timezone:2s}: {names}") + + +def get_timezone_selection(): + """Function for to select available timezones.""" + timezones = get_timezones_available() + while True: + selection = input(f"\nChoose a timezone to convert (1:{len(timezones)}): ").strip() + if selection in timezones: + return timezones[selection] + else: + print("Invalid selection") + + +def show_timezone_converted(): + """Function that displays the timezone selected by user """ + print("\n--- Time Zone Conversion ---") + print("\nSelect a time zone to see the current time in that part of the world") + print("\nAvailable timezones:") + show_timezones() + time_zone = get_timezone_selection() + display_time = datetime.now(ZoneInfo(time_zone[0])) + print(f"\nCurrent time in {time_zone[1]}: {display_time.strftime('%H:%M:%S')}") + diff --git a/projects/final-project/solution/danieleFiocca/simple_time_display/world_clock.py b/projects/final-project/solution/danieleFiocca/simple_time_display/world_clock.py new file mode 100644 index 0000000..85a48ca --- /dev/null +++ b/projects/final-project/solution/danieleFiocca/simple_time_display/world_clock.py @@ -0,0 +1,114 @@ +from datetime import datetime +from zoneinfo import ZoneInfo + + +def timezone_list(): + """Function that returns a list of all timezone names.""" + return { + '1': ('Europe/Rome', 'Rome, Italy'), + '2': ('Europe/London', 'London, United Kingdom'), + '3': ('America/New_York', 'New York, USA'), + '4': ('America/Los_Angeles', 'Los Angeles, USA'), + '5': ('Asia/Tokyo', 'Tokyo, Japan'), + '6': ('Asia/Shanghai', 'Shanghai, Cina'), + '7': ('Australia/Sydney', 'Sydney, Australia'), + '8': ('Europe/Paris', 'Parigi, France'), + '9': ('Asia/Dubai', 'Dubai, UAE'), + '10': ('America/Sao_Paulo', 'San Paolo, Brazil') + } + + +def display_available_timezones(): + print('Available timezones:') + for key, (tz, label) in timezone_list().items(): + print(f'{key}: {label}') + + +def select_timezone(): + timezones = timezone_list() + selection = input(f"Which timezone would you like to select (1: {len(timezones)})? ").strip() + if selection in timezones: + return timezones[selection] + + else: + print("That's not a valid timezone!") + return None + + +def add_clock(clocks): + """Function that adds a clock to the clocks list.""" + timezone = select_timezone() + if timezone and timezone not in clocks: + clocks.append(timezone) + print(f'Added {timezone[1]}') + elif timezone: + print(f'Timezone {timezone[1]} already exists') + return clocks + + +def get_clock_to_remove(clocks): + """Function that returns the timezone name to remove.""" + while True: + try: + index = int(input(f"Which timezone would you like to remove (1: {len(clocks)})? ")) + if 0 <= index < len(clocks): + return index + else: + print("That's not a valid timezone!") + except ValueError: + print("That's not a valid timezone!") + + +def remove_clock(clocks): + """Function that removes a clock from the clocks list.""" + if not clocks: + print("No clocks to remove") + return + + print("--- REMOVE CLOCK ---") + display_world_clocks(clocks) + + index = get_clock_to_remove(clocks) + removed = clocks.pop(index-1) + print(f'Removed {removed[1]}') + + + + +def display_world_clocks(clocks): + """Function that displays the clocks list.""" + print("\n--- WORLD CLOCK ---") + for tz_str, label in clocks: + now = datetime.now(ZoneInfo(tz_str)) + print(f'{label:25s}: {now.strftime("%Y-%m-%d %H:%M:%S")}') + print("============") + +def world_clock(): + """Function that displays the world clock.""" + clocks = [] + while True: + print("\nMenu:") + print("1. Show timezone clocks") + print("2. Add timezone clocks") + print("3. Remove timezone clocks") + print("4. Exit") + choiche = input("Select an option: ").strip() + if choiche == '1': + if clocks: + display_world_clocks(clocks) + else: + print("No clocks added yet") + + elif choiche == '2': + display_available_timezones() + add_clock(clocks) + + elif choiche == '3': + remove_clock(clocks) + + elif choiche == '4': + print("Quitting") + break + else: + print("That's not a valid option!") + From f5e5f2c31babea7bbb168ed0183d966951fb215f Mon Sep 17 00:00:00 2001 From: Daniele Fiocca Date: Tue, 24 Jun 2025 19:39:25 +0200 Subject: [PATCH 3/3] make correction after review --- .../simple_time_display/countdown_display.py | 61 ++++++++++++------- .../simple_time_display/current_time.py | 8 +-- .../simple_time_display/index.py | 50 ++++++++++++++- .../danieleFiocca/simple_time_display/main.py | 45 +------------- .../timezone_conversion.py | 27 ++++---- .../simple_time_display/world_clock.py | 54 ++++++++-------- 6 files changed, 136 insertions(+), 109 deletions(-) diff --git a/projects/final-project/solution/danieleFiocca/simple_time_display/countdown_display.py b/projects/final-project/solution/danieleFiocca/simple_time_display/countdown_display.py index 73d2327..a721b70 100644 --- a/projects/final-project/solution/danieleFiocca/simple_time_display/countdown_display.py +++ b/projects/final-project/solution/danieleFiocca/simple_time_display/countdown_display.py @@ -1,15 +1,12 @@ -import time import threading +import time def set_timer(): """Setting the timer in seconds""" - timer = int(input("Enter a time in seconds: ")) - while True: - if timer > 0: - return timer - else: - print("Value of timer must be greater than 0.") + while (timer := int(input("Enter time in seconds: "))) <= 0: + print("Invalid time. Time must be greater than 0.") + return timer def get_format_input(): @@ -34,22 +31,25 @@ def format_display_timer(seconds, format_selected): hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) if format_selected == 1: - return '{:02d}:{:02d}:{:02d}:{:02d}'.format(days, hours, minutes, seconds) + return "{:02d}:{:02d}:{:02d}:{:02d}".format(days, hours, minutes, seconds) if format_selected == 2: total_hours = days * 24 + hours - return '{:02d}:{:02d}:{:02d}'.format(total_hours, minutes, seconds) + return "{:02d}:{:02d}:{:02d}".format(total_hours, minutes, seconds) if format_selected == 3: total_minutes = (days * 24 * 60) + (hours * 60) + minutes - return '{:02d}:{:02d}'.format(total_minutes, seconds) + return "{:02d}:{:02d}".format(total_minutes, seconds) if format_selected == 4: - return '{:04d}'.format(seconds) + return "{:04d}".format(seconds) -def countdown_logic(initial_seconds, format_selected, pause_event, stop_event, reset_event): +def countdown_logic( + initial_seconds, format_selected, pause_event, stop_event, reset_event +): """Countdown logic""" seconds = initial_seconds while seconds >= 0: if stop_event.is_set(): + return if reset_event.is_set(): @@ -58,7 +58,11 @@ def countdown_logic(initial_seconds, format_selected, pause_event, stop_event, r print(f"\nReset to: {format_display_timer(seconds, format_selected)}") if not pause_event.is_set(): - print(f"\r{format_display_timer(seconds, format_selected)} ", end="", flush=True) + print( + f"\r{format_display_timer(seconds, format_selected)} ", + end="", + flush=True, + ) time.sleep(1) seconds -= 1 else: @@ -71,9 +75,25 @@ def handle_commands(pause, stop, reset): """Logic for threading commands""" print("Command available: start, pause, stop, reset") - while True: + while not stop.is_set(): command = input("\n>>>").strip().lower() - if command == "start": + match command: + case "start": + pause.clear() + print("time started") + case "pause": + pause.set() + print("time paused") + case "reset": + reset.set() + print("time reset") + case "stop": + stop.set() + print("time stopped") + + case _: + print("Invalid command") + """if command == "start": pause.clear() print("Timer started") elif command == "pause": @@ -87,11 +107,11 @@ def handle_commands(pause, stop, reset): print("Timer stopped") break else: - print("Command not available") + print("Command not available")""" def start_timer(): - """Function to start the timer """ + """Function to start the timer""" seconds = set_timer() format_selected = get_format_input() @@ -99,13 +119,12 @@ def start_timer(): stop = threading.Event() reset = threading.Event() - timer_thread = threading.Thread(target=countdown_logic, args=(seconds, format_selected, pause, stop, reset)) + timer_thread = threading.Thread( + target=countdown_logic, args=(seconds, format_selected, pause, stop, reset) + ) timer_thread.start() handle_commands(pause, stop, reset) timer_thread.join() print("\nTimer finished.") - - - diff --git a/projects/final-project/solution/danieleFiocca/simple_time_display/current_time.py b/projects/final-project/solution/danieleFiocca/simple_time_display/current_time.py index 6b6f3c7..3484da2 100644 --- a/projects/final-project/solution/danieleFiocca/simple_time_display/current_time.py +++ b/projects/final-project/solution/danieleFiocca/simple_time_display/current_time.py @@ -2,19 +2,19 @@ def current_date_time(): - return datetime.now().strftime('%d/%m/%Y %H:%M:%S') + return datetime.now().strftime("%d/%m/%Y %H:%M:%S") def day_of_the_week(): - return datetime.now().strftime('%A') + return datetime.now().strftime("%A") def day_of_the_year(): - return datetime.now().strftime('%j') + return datetime.now().strftime("%j") def week_number(): - return datetime.now().strftime('%W') + return datetime.now().strftime("%W") def show_date_time(): diff --git a/projects/final-project/solution/danieleFiocca/simple_time_display/index.py b/projects/final-project/solution/danieleFiocca/simple_time_display/index.py index b7377c5..8729318 100644 --- a/projects/final-project/solution/danieleFiocca/simple_time_display/index.py +++ b/projects/final-project/solution/danieleFiocca/simple_time_display/index.py @@ -1,4 +1,48 @@ -from main import main +def show_menu(): + """Function to display menu""" + print("--- Simple Time Display ---") + print("1. Display time with additional date information") + print("2. Time zone conversion") + print("3. Set a countdown") + print("4. World clock collection") + print("5. Exit") -if __name__ == '__main__': - main() + +def choose_menu(): + """function to select in menu""" + choice = input("Select an option: ").strip() + return choice + + +def elaborate_choice(choice): + """function to elaborate choice""" + while choice in ["1", "2", "3", "4", "5"]: + if choice == "1": + from current_time import show_date_time + + show_date_time() + elif choice == "2": + from timezone_conversion import show_timezone_converted + + show_timezone_converted() + elif choice == "3": + from countdown_display import start_timer + + start_timer() + elif choice == "4": + from world_clock import world_clock + + world_clock() + elif choice == "5": + print("Thank you for using this program!") + exit() + else: + print("Invalid selection.") + + +def main(): + """Main function""" + while True: + show_menu() + choice = choose_menu() + elaborate_choice(choice) diff --git a/projects/final-project/solution/danieleFiocca/simple_time_display/main.py b/projects/final-project/solution/danieleFiocca/simple_time_display/main.py index d16c62b..a072ece 100644 --- a/projects/final-project/solution/danieleFiocca/simple_time_display/main.py +++ b/projects/final-project/solution/danieleFiocca/simple_time_display/main.py @@ -1,43 +1,4 @@ -def show_menu(): - """Function to display menu""" - print("--- Simple Time Display ---") - print("1. Display time with additional date information") - print("2. Time zone conversion") - print("3. Set a countdown") - print("4. World clock collection") - print("5. Exit") +from index import main - -def choose_menu(): - """function to select in menu""" - choice = input("Select an option: ").strip() - return choice - - -def elaborate_choice(choice): - """function to elaborate choice""" - while choice in ["1", "2", "3", "4", "5"]: - if choice == "1": - from current_time import show_date_time - show_date_time() - elif choice == "2": - from timezone_conversion import show_timezone_converted - show_timezone_converted() - elif choice == "3": - from countdown_display import start_timer - start_timer() - elif choice == "4": - from world_clock import world_clock - world_clock() - elif choice == "5": - print("Thank you for using this program!") - exit() - else: - print("Invalid selection.") - -def main(): - """Main function""" - while True: - show_menu() - choice = choose_menu() - elaborate_choice(choice) +if __name__ == "__main__": + main() diff --git a/projects/final-project/solution/danieleFiocca/simple_time_display/timezone_conversion.py b/projects/final-project/solution/danieleFiocca/simple_time_display/timezone_conversion.py index 938b3ef..e689cfd 100644 --- a/projects/final-project/solution/danieleFiocca/simple_time_display/timezone_conversion.py +++ b/projects/final-project/solution/danieleFiocca/simple_time_display/timezone_conversion.py @@ -5,16 +5,16 @@ def get_timezones_available(): """Function for retrieving available timezones.""" return { - '1': ('Europe/Rome', 'Rome, Italy'), - '2': ('Europe/London', 'London, United Kingdom'), - '3': ('America/New_York', 'New York, USA'), - '4': ('America/Los_Angeles', 'Los Angeles, USA'), - '5': ('Asia/Tokyo', 'Tokyo, Japan'), - '6': ('Asia/Shanghai', 'Shanghai, China'), - '7': ('Australia/Sydney', 'Sydney, Australia'), - '8': ('Europe/Paris', 'Paris, France'), - '9': ('Asia/Dubai', 'Dubai, UAE'), - '10': ('America/Sao_Paulo', 'São Paulo, Brazil') + "1": ("Europe/Rome", "Rome, Italy"), + "2": ("Europe/London", "London, United Kingdom"), + "3": ("America/New_York", "New York, USA"), + "4": ("America/Los_Angeles", "Los Angeles, USA"), + "5": ("Asia/Tokyo", "Tokyo, Japan"), + "6": ("Asia/Shanghai", "Shanghai, China"), + "7": ("Australia/Sydney", "Sydney, Australia"), + "8": ("Europe/Paris", "Paris, France"), + "9": ("Asia/Dubai", "Dubai, UAE"), + "10": ("America/Sao_Paulo", "São Paulo, Brazil"), } @@ -29,7 +29,9 @@ def get_timezone_selection(): """Function for to select available timezones.""" timezones = get_timezones_available() while True: - selection = input(f"\nChoose a timezone to convert (1:{len(timezones)}): ").strip() + selection = input( + f"\nChoose a timezone to convert (1:{len(timezones)}): " + ).strip() if selection in timezones: return timezones[selection] else: @@ -37,7 +39,7 @@ def get_timezone_selection(): def show_timezone_converted(): - """Function that displays the timezone selected by user """ + """Function that displays the timezone selected by user""" print("\n--- Time Zone Conversion ---") print("\nSelect a time zone to see the current time in that part of the world") print("\nAvailable timezones:") @@ -45,4 +47,3 @@ def show_timezone_converted(): time_zone = get_timezone_selection() display_time = datetime.now(ZoneInfo(time_zone[0])) print(f"\nCurrent time in {time_zone[1]}: {display_time.strftime('%H:%M:%S')}") - diff --git a/projects/final-project/solution/danieleFiocca/simple_time_display/world_clock.py b/projects/final-project/solution/danieleFiocca/simple_time_display/world_clock.py index 85a48ca..836e0ef 100644 --- a/projects/final-project/solution/danieleFiocca/simple_time_display/world_clock.py +++ b/projects/final-project/solution/danieleFiocca/simple_time_display/world_clock.py @@ -5,28 +5,30 @@ def timezone_list(): """Function that returns a list of all timezone names.""" return { - '1': ('Europe/Rome', 'Rome, Italy'), - '2': ('Europe/London', 'London, United Kingdom'), - '3': ('America/New_York', 'New York, USA'), - '4': ('America/Los_Angeles', 'Los Angeles, USA'), - '5': ('Asia/Tokyo', 'Tokyo, Japan'), - '6': ('Asia/Shanghai', 'Shanghai, Cina'), - '7': ('Australia/Sydney', 'Sydney, Australia'), - '8': ('Europe/Paris', 'Parigi, France'), - '9': ('Asia/Dubai', 'Dubai, UAE'), - '10': ('America/Sao_Paulo', 'San Paolo, Brazil') + "1": ("Europe/Rome", "Rome, Italy"), + "2": ("Europe/London", "London, United Kingdom"), + "3": ("America/New_York", "New York, USA"), + "4": ("America/Los_Angeles", "Los Angeles, USA"), + "5": ("Asia/Tokyo", "Tokyo, Japan"), + "6": ("Asia/Shanghai", "Shanghai, Cina"), + "7": ("Australia/Sydney", "Sydney, Australia"), + "8": ("Europe/Paris", "Parigi, France"), + "9": ("Asia/Dubai", "Dubai, UAE"), + "10": ("America/Sao_Paulo", "San Paolo, Brazil"), } def display_available_timezones(): - print('Available timezones:') + print("Available timezones:") for key, (tz, label) in timezone_list().items(): - print(f'{key}: {label}') + print(f"{key}: {label}") def select_timezone(): timezones = timezone_list() - selection = input(f"Which timezone would you like to select (1: {len(timezones)})? ").strip() + selection = input( + f"Which timezone would you like to select (1: {len(timezones)})? " + ).strip() if selection in timezones: return timezones[selection] @@ -40,9 +42,9 @@ def add_clock(clocks): timezone = select_timezone() if timezone and timezone not in clocks: clocks.append(timezone) - print(f'Added {timezone[1]}') + print(f"Added {timezone[1]}") elif timezone: - print(f'Timezone {timezone[1]} already exists') + print(f"Timezone {timezone[1]} already exists") return clocks @@ -50,7 +52,9 @@ def get_clock_to_remove(clocks): """Function that returns the timezone name to remove.""" while True: try: - index = int(input(f"Which timezone would you like to remove (1: {len(clocks)})? ")) + index = int( + input(f"Which timezone would you like to remove (1: {len(clocks)})? ") + ) if 0 <= index < len(clocks): return index else: @@ -69,10 +73,8 @@ def remove_clock(clocks): display_world_clocks(clocks) index = get_clock_to_remove(clocks) - removed = clocks.pop(index-1) - print(f'Removed {removed[1]}') - - + removed = clocks.pop(index - 1) + print(f"Removed {removed[1]}") def display_world_clocks(clocks): @@ -83,6 +85,7 @@ def display_world_clocks(clocks): print(f'{label:25s}: {now.strftime("%Y-%m-%d %H:%M:%S")}') print("============") + def world_clock(): """Function that displays the world clock.""" clocks = [] @@ -92,23 +95,22 @@ def world_clock(): print("2. Add timezone clocks") print("3. Remove timezone clocks") print("4. Exit") - choiche = input("Select an option: ").strip() - if choiche == '1': + choice = input("Select an option: ").strip() + if choice == "1": if clocks: display_world_clocks(clocks) else: print("No clocks added yet") - elif choiche == '2': + elif choice == "2": display_available_timezones() add_clock(clocks) - elif choiche == '3': + elif choice == "3": remove_clock(clocks) - elif choiche == '4': + elif choice == "4": print("Quitting") break else: print("That's not a valid option!") -