You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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) and sumN (to hold the total sum) set to 0.
  • Infinite Loop: while True runs forever until we hit the break statement.
  • 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-except block here—this is the right place for it! If the input can be converted to a float, we add it to our sum, increment the count, and print the number. If not (like if someone types 'stop'), we catch the ValueError and 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-except block 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:34:44