|
| 1 | +import time |
| 2 | + |
| 3 | + |
| 4 | +def countdown(minutes: int, label: str) -> None: |
| 5 | + """Print a mm:ss countdown once per second for the given label.""" |
| 6 | + total_seconds = minutes * 60 |
| 7 | + while total_seconds >= 0: |
| 8 | + mins, secs = divmod(total_seconds, 60) |
| 9 | + print(f"{label} Timer: {mins:02d}:{secs:02d}", end="\r") |
| 10 | + time.sleep(1) |
| 11 | + total_seconds -= 1 |
| 12 | + print(f"\n{label} finished!") |
| 13 | + |
| 14 | +def handle_pause_stop() -> bool: |
| 15 | + while True: |
| 16 | + user_input = input( |
| 17 | + "\nPress 'p' to pause, 's' to stop, or 'Enter' to continue: " |
| 18 | + ).lower() |
| 19 | + if user_input == "p": |
| 20 | + print("Timer paused. Press 'Enter' to resume.") |
| 21 | + input() |
| 22 | + elif user_input == "s": |
| 23 | + print("Timer stopped.") |
| 24 | + return True # Return True to signal that the timer should stop |
| 25 | + else: |
| 26 | + return False # Return False to continue with the timer |
| 27 | + |
| 28 | + |
| 29 | +def pomodoro_timer(work_min, short_break_min, long_break_min, cycles): |
| 30 | + for i in range(cycles): |
| 31 | + print(f"\nCycle {i+1} of {cycles}") |
| 32 | + countdown(work_min, "Work") |
| 33 | + if i < cycles - 1: |
| 34 | + print("\nStarting short break...") |
| 35 | + if handle_pause_stop(): |
| 36 | + return |
| 37 | + countdown(short_break_min, "Short Break") |
| 38 | + else: |
| 39 | + print("\nStarting long break...") |
| 40 | + if handle_pause_stop(): |
| 41 | + return |
| 42 | + countdown(long_break_min, "Long Break") |
| 43 | + if not repeat_or_end(): |
| 44 | + return |
| 45 | + |
| 46 | + |
| 47 | +def repeat_or_end(): |
| 48 | + user_input = input( |
| 49 | + "\nCycle finished. Would you like to repeat the cycle? (y/n): " |
| 50 | + ).lower() |
| 51 | + return user_input == "y" |
| 52 | + |
| 53 | + |
| 54 | +def get_valid_input(prompt): |
| 55 | + while True: |
| 56 | + try: |
| 57 | + value = int(input(prompt)) |
| 58 | + if value <= 0: |
| 59 | + raise ValueError |
| 60 | + return value |
| 61 | + except ValueError: |
| 62 | + print("Invalid input. Please enter a positive integer.") |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + work_minutes = get_valid_input("Enter work interval in minutes: ") |
| 67 | + short_break_minutes = get_valid_input("Enter short break interval in minutes: ") |
| 68 | + long_break_minutes = get_valid_input("Enter long break interval in minutes: ") |
| 69 | + cycles = get_valid_input("Enter the number of cycles: ") |
| 70 | + |
| 71 | + while True: |
| 72 | + pomodoro_timer(work_minutes, short_break_minutes, long_break_minutes, cycles) |
| 73 | + # If user chose to repeat at the end, loop continues; otherwise we break here. |
| 74 | + if not repeat_or_end(): |
| 75 | + break |
0 commit comments