Python编程求助:编写循环接收数字输入直至输入'complete'的程序
Solution for Your Number Input Loop
Hey there! As a fellow Python learner, let's walk through fixing this code to match exactly what you need. Your original code has some logic mix-ups (like using 'done' instead of 'complete' and misplaced error handling), so let's rebuild it properly.
The Correct Approach
Here's a cleaned-up version that meets all your requirements:
count = 0 sumN = 0.0 while True: user_input = input('>>> ') # Check if user wants to finish if user_input.strip().lower() == 'complete': break # Try to convert input to a number try: number = float(user_input) print(number) # Print the valid number sumN += number count += 1 except ValueError: # If input isn't a number or 'complete', show a hint print("Oops! Please enter a valid number or type 'complete' to finish.") # After exiting the loop, calculate and show results if count > 0: average = sumN / count print(f'\nThe total sum of your inputs is: {sumN}') print(f'The count of your inputs is: {count}') print(f'The average of your inputs is: {average:.2f}') # Format to 2 decimal places for readability else: print("\nYou didn't enter any numbers!")
Let's Break Down What This Does
- Initialization: We start with
count(to track how many valid numbers were entered) andsumN(to hold the total sum) set to 0. - Infinite Loop:
while Trueruns forever until we hit thebreakstatement. - Check for Exit Command: First we check if the input is
'complete'(we use.strip()to ignore extra spaces and.lower()to make it case-insensitive, so 'Complete' or 'COMPLETE' also work!). - Validate Number Input: We use a
try-exceptblock here—this is the right place for it! If the input can be converted to afloat, we add it to our sum, increment the count, and print the number. If not (like if someone types 'stop'), we catch theValueErrorand show a friendly hint. - Final Results: Once the loop ends, we check if any numbers were entered (to avoid dividing by zero!). Then we print the sum, count, and average (formatted to 2 decimals for clarity).
What Was Wrong With the Original Code?
- The
try-exceptblock was placed incorrectly, so it was catching errors at the wrong time (like trying to convert 'done' to a float before checking if it's the exit command). - It used 'done' instead of the required 'complete' to exit.
- It had unnecessary checks for '#' which wasn't part of your requirements.
- It didn't handle non-number inputs properly (like 'stop') with a clear hint.
内容的提问来源于stack exchange,提问作者Jason Sic Narf Garnett
相关产品推荐
相关产品推荐

