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

求和与平均值计算出现‘Variable not defined’错误,求技术解决方案

Fixing Your Sum & Average Calculator: Resolving "Variable Not Defined" Error

Hey there! Let's walk through the issues in your code to fix that frustrating error and get your calculator running smoothly.

Key Issues in Your Code:

  • Undefined Variables (b and d): You referenced b and d in your print statement and calculation, but these variables were never created. Looking at your comments, you intended Sum to be your running total (not b), and d was supposed to be the average (which you never defined).
  • Missing Parenthesis: The line where you get user input for c is missing a closing parenthesis at the end—this breaks the syntax and can cause unexpected variable-related errors.
  • Incorrect Loop Range: Using range(a-1) means your loop will run one fewer time than the number of inputs the user specified. For example, if the user says they'll enter 3 numbers, the loop only runs 2 times.
  • Broken Average Calculation: The line Total=b/10 makes no sense here—you need to divide the total sum by the number of inputs (a), not 10, and use the correct variable for the sum.

Corrected Code:

a = int(input("Total Numbers you will input for calculation: "))
sum_total = 0  # Renamed for clarity, but you could keep "Sum" if preferred
for x in range(a):
    c = int(input("Enter your input number {0}.".format(x+1)))  # Added missing closing parenthesis
    sum_total = sum_total + c
average = sum_total / a  # Calculate average correctly
print("Total sum of the numbers you entered is {0} and their average is {1}.".format(sum_total, average))

What Changed:

  1. Replaced undefined b with sum_total (your actual running total variable)
  2. Created an average variable to store the calculated average (instead of the undefined d)
  3. Fixed the missing parenthesis in the input line
  4. Changed range(a-1) to range(a) so the loop runs the correct number of times
  5. Updated the average calculation to divide the sum by the number of inputs (a)
  6. Cleaned up variable names for better readability (optional, but helps avoid confusion)

Give this a run, and it should work exactly as you intended!

内容的提问来源于stack exchange,提问作者Trailokya Raj Bajgain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:05:58