我试图让这个程序给我一个看起来像这样的输出:
Enter a number (-9999 to end): 4
Enter a number (-9999 to end): -3
Enter a number (-9999 to end): -15
Enter a number (-9999 to end): 0
Enter a number (-9999 to end): 10
Enter a number (-9999 to end): 22
Enter a number (-9999 to end): -9999
The list of all numbers entered is:
[4, -3, -15, 0, 10, 22]
The dictionary with averages is:
{'AvgPositive': 12.0, 'AvgNonPos': -6.0, 'AvgAllNum': 3.0}
这是我到目前为止的代码,但它显然不起作用。任何帮助表示赞赏,但请在代码中显示。大多数情况下,我无法获得"平均字典是: {' AvgPositive':12.0,' AvgNonPos':-6.0,' AvgAllNum':3.0}"
def nums():
values = []
while -9999 not in values:
x = int(input("Enter a number (-9999 to end: )"))
values.append(x)
values.remove(-9999)
return values
def allNumAvg(values):
average = 0
sum = 0
for n in values:
sum = sum + n
average = sum / len(values)
return average
def avgNonPos(values):
return allNumAvg([v for v in values if v<0])
if int in values < 0:
x.append(int)
print(x)
return average
def posNumAvg(values):
return allNumAvg([v for v in values if v>0])
if int in values > 0:
x.append(int)
print(x)
input(print("'AvgPositive': ",posNumAvg(nums())),"'AvgNonPos': ",avgNonPos(nums())),"'AvgAllNum': ",allNumAvg(nums())
答案 0 :(得分:0)
我认为你在这里写错了一些东西:
为了便于阅读我省略了if条件并修复了你的print语句,我认为这是你想要实现的目标:
def nums():
values = []
while -9999 not in values:
x = int(input("Enter a number (-9999 to end: )"))
values.append(x)
values.remove(-9999)
return values
def allNumAvg(values):
average = 0
sum = 0
for n in values:
sum = sum + n
average = sum / len(values)
return average
def avgNonPos(values):
return allNumAvg([v for v in values if v < 0])
def posNumAvg(values):
return allNumAvg([v for v in values if v > 0])
values = nums()
print "'AvgPositive': ", posNumAvg(values)
print "'AvgNonPos': ", avgNonPos(values)
print "'AvgAllNum': ", allNumAvg(values)
如果这是正确的,或者您需要任何其他功能,请告诉我。
答案 1 :(得分:0)
这将是一个按预期工作的代码版本(我希望)
def nums():
values = []
while -9999 not in values:
x = int(input("Enter a number (-9999 to end: )"))
values.append(x)
values.remove(-9999)
return values
def allNumAvg(values):
return sum(values) / len(values)
def avgNonPos(values):
return allNumAvg([v for v in values if v < 0])
def posNumAvg(values):
return allNumAvg([v for v in values if v > 0])
if __name__ == "__main__":
values = nums()
print("The list of all numbers entered is:")
print(values)
print("The dictionary with averages is:")
print({'AvgPositive': posNumAvg(values), 'AvgNonPos': avgNonPos(values), 'AvgAllNum': allNumAvg(values)})
注意事项:
1:两次调用nums()(在下面的代码中)意味着将收集两次数字,这是不希望的
input(print("'AvgPositive': ",posNumAvg(nums())),"'AvgNonPos': ",avgNonPos(nums())),"'AvgAllNum': ",allNumAvg(nums())
在我的代码示例中,您可以看到nums()被调用一次并保存在稍后传递的值中。
2:avgNonPos / posNumAvg中的以下代码是死代码。即它不会运行,因为它存在于return语句之后。
if int in values > 0:
x.append(int)
3:我使用内置函数sum()
清理了allNumAvg(values)函数