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

Python程序开发求助:实现自定义数量数字的求和及平均值计算功能

Got it, let's fix this up for you! Your current code has some logic snags (like duplicate input prompts and incorrect use of sum()), so here's a clean, working version that does exactly what you need—copy-paste it and it'll run right away:

Working Python Program for Sum & Average Calculation
# Ask user how many numbers they want to enter
number_count = int(input("How many numbers would you like to input? "))

# Initialize total sum to 0
total_sum = 0

# Loop to collect each number and add to the total
for i in range(number_count):
    current_num = int(input(f"Enter number {i + 1}: "))
    total_sum += current_num

# Calculate average (sum divided by number of inputs)
average = total_sum / number_count

# Print out the results clearly
print(f"\nTotal sum of your numbers: {total_sum}")
print(f"Average of your numbers: {average}")

Quick Breakdown of How This Works

  • Get input count: First we ask for the number of values you want to enter, converting the input to an integer since we need a whole number.
  • Track total sum: We start with a total of 0, then add each input number to this total as we go.
  • Simpler loop: A for loop is perfect here because we know exactly how many times we need to ask for input (no messy counter checks like in your original code).
  • Calculate average: Just divide the total sum by the number of inputs—easy!
  • Clear output: We print both the sum and average so you can see both results at a glance.

What Was Off in Your Original Code?

  • You had duplicate "next number" prompts when your counter hit the target, which would make you enter extra numbers by mistake.
  • The sum() function is meant for iterables (like lists), not for adding two variables directly with sum(number + num).
  • You repeated the same counter == strike condition twice, which didn't add any useful logic.

内容的提问来源于stack exchange,提问作者the_wilche

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 20:59:04