【发布时间】:2015-06-23 04:59:53
【问题描述】:
与往常一样,在我继续在这里提问之前,我已经尝试了一段时间。我知道有几次尝试回答这个问题,但没有一个能真正满足我的需要。
以下是说明:
实现以下三个函数(您应该使用适当的循环结构来计算平均值):
allNumAvg(numList) : takes a list of numbers and returns the average of all the numbers in the list.
posNumAvg(numList) : takes a list of numbers and returns the average of all the numbers in the list that are greater than zero.
nonPosAvg(numList) : takes a list of numbers and returns the average of all the numbers in the list that are less than or equal to zero.
编写一个程序,要求用户输入一些数字(正数、负数和零)。您的程序不应要求用户输入固定数量的数字。此外,它不应该询问用户想要输入的数字数量。但它应该要求用户输入一些数字并以 -9999(一个标记值)结尾。用户可以按任何顺序输入数字。您的程序不应要求用户分别输入正数和负数。
然后您的程序应该创建一个包含输入数字的列表(确保不在此列表中包含标记值 (-9999))并输出列表和具有以下键值对的字典(使用输入列表及以上功能):
Key = 'AvgPositive' : Value = the average of all the positive numbers
Key = 'AvgNonPos' : Value = the average of all the non-positive numbers
Key = 'AvgAllNum' : Value = the average of all the numbers
示例运行:
输入一个数字(-9999 结束):4
输入一个数字(-9999 结束):-3
输入一个数字(-9999 结束):-15
输入一个数字(-9999 结束):0
输入一个数字(-9999 结束):10
输入一个数字(-9999 结束):22
输入一个数字(-9999 结束):-9999
输入的所有数字的列表是:
[4, -3, -15, 0, 10, 22]
具有平均值的字典是:
{'AvgPositive':12.0,'AvgNonPos':-6.0,'AvgAllNum':3.0}
这是我的代码:
a = []
b = []
c = []
dictionary = {}
total = 0
print("Enter positive, negative or zero to determine the average: ")
while(True):
user_input = int(input("Enter a number (-9999 to end): "))
if(user_input == -9999):
break
def allNumAvg(values):
for number in a:
total = total + number
average = sum(total) / len(total)
if user_input > 0 or user_input < 0:
a.append(user_input)
return average
def posNumAvg(values):
for number in b:
total = total + number
average = sum(total) / len(total)
if user_input > 0:
b.append(user_input)
return average
def nonPosAvg(values):
for number in c:
total = total + number
average = sum(total) + len(total)
if user_input < 0:
c.append(user_input)
return average
print("The list of all numbers entered is:")
print(a+b+c)
dictionary = {
"AvgPositive": posNumAvg(values),
"AvgNonPos": nonPosAvg(values),
"AvgAllNum": allNumAvg(values)
}
print("The dictionary with the averages are:")
print(dictionary)
我的问题是如何实现从字典中打印的平均值,因为我目前遇到的错误是:"AvgPositive": posNumAvg(values), NameError: name 'values' is not defined。此外,如何获取输入的数字列表以进行打印?
谢谢!
【问题讨论】:
-
您似乎对参数和引用有些困惑。你可以阅读更多关于函数here。
-
我认为您没有在任何地方声明 values 变量
-
values实际上是声明的,但只是作为每个函数的形参。
标签: python list dictionary