【问题标题】:PYTHON: Why does "varaible=float(variable)/len(variable2)" work, but "variable=float(variable) variable/len(variable2)" does not work?PYTHON:为什么“variable=float(variable)/in(variable 2)”有效,但“variable=float(variable) variable/len(variable2)”无效?
【发布时间】:2017-04-12 15:53:18
【问题描述】:
lloyd = {
  "name": "Lloyd",
  "homework": [90.0, 97.0, 75.0, 92.0],
  "quizzes": [88.0, 40.0, 94.0],
  "tests": [75.0, 90.0]
{

alice = {
  "name": "Alice",
  "homework": [100.0, 92.0, 98.0, 100.0],
  "quizzes": [82.0, 83.0, 91.0],
  "tests": [89.0, 97.0]
}

tyler = {
  "name": "Tyler",
  "homework": [0.0, 87.0, 75.0, 22.0],
  "quizzes": [0.0, 75.0, 78.0],
  "tests": [100.0, 100.0]
}

# Add your function below!
def average(numbers):
  total=sum(numbers)
  total=float(total)
  total/len(numbers)
  return total
print total

test = lloyd['homework']

average(test)`

当我测试平均值时,它的返回值与 varaible=float(variable)/len(variable2) 不同

对不起,我是新手,格式不好

【问题讨论】:

  • total/len(numbers) 什么都不做。你的意思是total/=len(numbers) 吗? 那个会起作用
  • total/len(numbers) 你没有存储这个结果(这是你想要的)。

标签: python dictionary


【解决方案1】:

您应该返回total/len(numbers)。实际上,您计算平均值,但随后对该值不做任何事情,因此将其丢弃。

def average(numbers):
    total=sum(numbers)
    total=float(total)
    avg = total/len(numbers)
    print(avg)
    return avg

【讨论】:

  • 非常感谢!
  • 如果我想打印总数,我可以把print total/len(numbers)放在return行下面吗?
  • 没有。当函数返回时,程序完全退出该函数。它永远不会到达回报。要打印平均值并返回它,您可以将平均值分配给变量avg = total/len(numbers),然后打印它并返回它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-06
  • 1970-01-01
  • 2022-08-17
  • 1970-01-01
  • 2019-11-16
相关资源
最近更新 更多