简体   繁体   English

将 function 的返回值存储在变量中

[英]Store the return of a function in variable

I'm learning python, and I'm having trouble saving the return of a function to a specific variable.我正在学习 python,并且无法将 function 的返回值保存到特定变量。 I have computed a simple function 'average' that is supposed to return the average value of a list.我计算了一个简单的 function 'average',它应该返回列表的平均值。 This works fine, however, when I try to store the result of average in a variable, I get told that x isn't defined.这很好用,但是,当我尝试将平均值的结果存储在变量中时,我被告知 x 未定义。

def average(x):
    return sum(x)/len(x)

var=average(x)

How do I store the return of the function in a variable?如何将 function 的返回值存储在变量中?

Edit: I misunderstood the task, which was simply to store the results of a specific computation in a variable.编辑:我误解了任务,它只是将特定计算的结果存储在变量中。

x indeed is not defined x确实没有定义

def average(x):
    return sum(x)/len(x)

x = [1,2,3] # this was missing

var=average(x)

https://repl.it/join/eldrjqcr-datamafia https://repl.it/join/eldrjqcr-datamafia

The function is a black box. function 是一个黑盒子。 You made the black box expect one mandatory input ( x ), therefore you have to provide it first ie var = average([1, 2, 3]) .您使黑匣子需要一个强制输入( x ),因此您必须首先提供它,即var = average([1, 2, 3])

Read the error message, x isn't defined.阅读错误消息,x 未定义。 The variable x exists only in the average function and not in the program.变量 x 仅存在于平均 function 中,而不存在于程序中。 You need to set x to something first.您需要先将 x 设置为某个值。 eg例如

def average(x):
    return sum(x)/len(x)
x=[1,2,3]
var=average(x)

this will not cause an error这不会导致错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM