简体   繁体   中英

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. I have computed a simple function 'average' that is supposed to return the average value of a list. This works fine, however, when I try to store the result of average in a variable, I get told that x isn't defined.

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

var=average(x)

How do I store the return of the function in a variable?

Edit: I misunderstood the task, which was simply to store the results of a specific computation in a variable.

x indeed is not defined

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

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

var=average(x)

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

The function is a black box. You made the black box expect one mandatory input ( x ), therefore you have to provide it first ie var = average([1, 2, 3]) .

Read the error message, x isn't defined. The variable x exists only in the average function and not in the program. You need to set x to something first. eg

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

this will not cause an error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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