Python时间时长计算器Continue/Clear功能实现技术求助
Fixing Continue/Clear Functionality for Your Time Duration Calculator
Hey there! Nice start on your time calculator—great idea for a first project. Let's get that Continue/Clear logic working smoothly so you can keep adding durations without restarting the program every time.
The Core Issue with Your Current Code
Right now, your code only handles one round of adding two durations, and the post-calculation loop just checks the user's input without actually updating the total or resetting the state. We need to wrap the entire workflow in a main loop that maintains a running total, and adjust the input flow based on whether we're starting fresh or continuing from a previous total.
Revised Code with Working Continue/Clear
Here's the updated version with comments explaining each key change:
import datetime def get_time_input(prompt): """Helper function to get valid time input from the user""" print(prompt) while True: try: seconds = int(input("Seconds: ")) minutes = int(input("Minutes: ")) hours = int(input("Hours: ")) # Ensure non-negative values (since durations can't be negative) if seconds < 0 or minutes < 0 or hours < 0: print("Please enter non-negative numbers only.") continue return datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds) except ValueError: print("Invalid input—please enter integers for seconds, minutes, and hours.") # Initialize running total to 0 (start fresh) total_duration = datetime.timedelta(0) print("=== Time Duration Calculator ===") while True: # If total is 0, we're starting fresh (initial state or after Clear) if total_duration == datetime.timedelta(0): new_duration = get_time_input("\nEnter your first time duration:") else: # If we're continuing, only ask for the next duration new_duration = get_time_input("\nEnter the next time duration:") # Add the new duration to our running total total_duration += new_duration print(f"\nCurrent Total: {total_duration}") # Get user choice for next action while True: choice = input("\nContinue adding? (Y) | Clear total? (N) | Exit? (X): ").strip().upper() if choice in ["Y", "YES"]: # Keep the running total, loop back to ask for next duration break elif choice in ["N", "NO"]: # Reset total to 0, go back to initial state total_duration = datetime.timedelta(0) print("\nTotal cleared—ready for new calculations.") break elif choice in ["X", "EXIT"]: print("\nExiting calculator. Thanks for using it!") exit() else: print("Invalid input—please enter Y, N, or X.")
Key Improvements Explained
- Running Total Variable:
total_durationkeeps track of the sum, starting at 0. When you choose Continue, we just add the new input to this total. When you choose Clear, we reset it to 0. - Helper Function:
get_time_input()reduces code repetition and adds validation to make sure users enter valid non-negative integers. - Main Loop: The outer
while Trueloop keeps the program running until the user chooses Exit. - Conditional Input Flow: If the total is 0 (initial or cleared), we ask for the "first" duration; otherwise, we ask for the "next" one—matches your requirement perfectly.
How It Works in Practice
- Initial State: You enter the first time, get a total, then choose Y to add another time (only need to enter the next one), N to reset, or X to exit.
- Continue: The previous total stays, you input the next duration, and the new sum is displayed.
- Clear: The total resets to 0, and you're prompted to enter a new first duration again.
内容的提问来源于stack exchange,提问作者Arryn McLean
相关产品推荐
相关产品推荐

