本人在编写嵩天老师的课程中基本统计值计算时,多次修改代码都在报错,我查了下是关于符号问题的。奈何逐条对比正确答案仍未找到修改办法。恳求大佬有空帮解决下问题。
下面附上**代码和报错信息**。
#CalStatistticsV1.py
def getNum(): #获得用户输入数字
nums = []
iNumStr = input("请输入数字(回车退出):")
while iNumStr != " ":
nums.append(eval(iNumStr))
iNumStr = input("请输入数字(回车退出):")
return nums
def mean(numbers): #求平均值
s=0.0
for num in numbers:
s = s + num
return s / len(numbers)
def dev(numbers,mean): #计算方差
sdev = 0.0
for num in numbers:
sdev = sdev + (num-mean)**2
return pow(sdev / (len(numbers)-1),0.5)
def median(numbers): #计算中位数
sorted(numbers)
size = len(numbers)
if size % 2 == 0:
med=(numbers[size//2-1]+numbers[size//2])/2
else:
med=numbers[size//2]
return med
n = getNum() #主体函数
m = mean(n)
print("平均值:{},方差:{},中位数:{}".format(m,dev(n,m),median(n)))
报错信息:
Traceback (most recent call last):
File "E:\study&workingapp\python\Python_app\CalStatisticsV1.py", line 31, in
n = getNum() #主体函数
File "E:\study&workingapp\python\Python_app\CalStatisticsV1.py", line 6, in getNum
nums.append(eval(iNumStr))
File "", line 0
^
SyntaxError: unexpected EOF while parsing
正确代码:
#CalStatisticsV1.py
def getNum(): #获取用户不定长度的输入
nums = []
iNumStr = input("请输入数字(回车退出): ")
while iNumStr != "":
nums.append(eval(iNumStr))
iNumStr = input("请输入数字(回车退出): ")
return nums
def mean(numbers): #计算平均值
s = 0.0
for num in numbers:
s = s + num
return s / len(numbers)
def dev(numbers, mean): #计算方差
sdev = 0.0
for num in numbers:
sdev = sdev + (num - mean)**2
return pow(sdev / (len(numbers)-1), 0.5)
def median(numbers): #计算中位数
sorted(numbers)
size = len(numbers)
if size % 2 == 0:
med = (numbers[size//2-1] + numbers[size//2])/2
else:
med = numbers[size//2]
return med
n = getNum() #主体函数
m = mean(n)
print("平均值:{},方差:{:.2},中位数:{}.".format(m, dev(n,m),median(n)))