总计算和平均计算中的“未定义变量”错误

时间:2018-04-03 03:14:17

标签: python variables

我编写了这个程序来查找sum和average,并得到了“Variable not defined”错误。有人能解决吗?

a=int(input("Total Numbers you will input for calculation: "))
Sum = 0 # Running Totalis b
for x in range (a-1):
    c=int(input("Enter your input number {0}.".format(x+1)) # c is for next number
    Sum = Sum + c
Total=b/10 # For Total
print("Total sum of the number you entered is {0} and their average is {1},".format(b,d))

2 个答案:

答案 0 :(得分:0)

在打印出总和和平均值的代码中,您可以参考变量bd,它们实际上都不存在。这就是您当前问题的原因,即“未定义变量”问题。

数字的总和存储在您应该使用的Sum变量中,而不是b平均值不会在任何地方计算,除非您的Total计算意图执行此操作,但如果是这种情况,则应选择更合适的名称​​和计算它正确(除以a而不是10)。

最重要的是,你对范围的使用是不正确的。您应该使用a而不是a-1,因为range(n) 已经为您提供值0 .. n-1n不同的count = int(input("Total Numbers you will input for calculation: ")) if count > 0: sumOfNums = 0 for x in range(count): num = int(input("Enter your input number {0}.".format(x+1)) sumOfNums += num avgOfNums = sumOfNums / count print("Total sum of the number you entered is {0} and their average is {1},".format(sumOfNums, avgOfNums)) 项目

因此,考虑到所有这些,并使用一些更好的(自我记录)变量名称(并且捕捉到输入非正数的问题),您可以选择以下内容:

ConstraintLayout

答案 1 :(得分:-1)

看看下面的内容:

a=int(input("Total Numbers you will input for calculation: "))
sum = 0 # Running Totalis b
for x in range (a):
    c=int(input("Enter your input number {0}.".format(x+1)))
    sum +=c
avg=sum / a # For Total
print("Total sum of the number you entered is {0} and their average is {1},".format(sum,avg))
相关问题