How could I reach an element within a def function. I want to compute mean
by using p
which is inside of the def function.
import numpy as np
k= np.array([1,2,3,4,5,6])
def func():
p = k + 5
l = k + 25
func()
mean = p + 10
How could I reach an element within a def function. I want to compute mean
by using p
which is inside of the def function.
import numpy as np
k= np.array([1,2,3,4,5,6])
def func():
p = k + 5
l = k + 25
func()
mean = p + 10
When functions are done executing, all references to the variables within the function are cleared and removed from the stack. To get the values in the function, you have to use the return
keyword.
Example:
def test_return_string():
return "Hello World"
my_var = test_return_string() # "Hello world" is returned and stored in my_var
print(my_var) # Prints "Hello world"
When you do not define a return
statement for the function. The function will return None
by default.
Do note that returning a function will end its execution.
TL;DR - To get the variable p, you would just have to return p
at the end of the function.
import numpy as np
k= np.array([1,2,3,4,5,6])
def func(k):
p = k + 5
l = k + 25
return(p,l)
p,l= func(k)
mean = p + 10
import numpy as np
k= np.array([1,2,3,4,5,6])
def func(k):
p = k + 5
l = k + 25
return p
mean = func(k) + 10
Here, I tried to make the more compact example with the less changes relative to your post.
When you def a function, in general you want to pass a variable through as argument to make the output related to the variable. So you def func(variable):
, here def func(k):
. That was the first "mistake".
Then, if you want the function to return a result, you need the return
statement. That was the second "mistake".
Finally, if you want to use what the function returns, you need either to store the result in a variable, either to use it "in-place".
func(k)
does not print (excepted in the python shell) nor assigns a value to a variable. It is just running and that's it.
print(func(k))
shows the result in the terminal (for both script/python sheel), wheras p = func(k)
assign what func(k)
returns to variable p
. Then you can use p
to compute the mean as mean = p + 10
. Or you can directly use func(k)
instead, because it provides your mean calculation with the same value than p
(cause p = func(k)
)
Finally, in your function computing l seems to be useless now. So maybe think about removing it or using it within.