calling a function within def() outside of it [duplicate] - python

This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed 2 years ago.
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.

Related

A question regarding the Lambda function in Python

Why in the following code, the output is 22?
In my understanding, we have a function that needs two arguments, but it has been defined with only one! However, the first time we use it in mydoubler = myfunc(2), it assigns the argument(2) to variable n, but the second time we use it in print(mydoubler(11), it uses the argument(11) to set the value of the variable a! Why is that? Does Lambda work like a recursive function?
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Basically what happens is this:
mydoubler = myfunc(2) is actually the same as writing mydoubler = lambda a : a * 2
The reason for this is that myfunc(2) returns lambda a : a * 2
So now mydoubler = lambda a : a * 2
Then when mydoubler(11) is called, it simply returns 11 * 2
You're returning a lambda, which is a one-liner function, NOT a number. The code below does the EXACT SAME thing, but is maybe a bit clearer as to its purpose:
def multiplier_factory(constant_factor):
# Define our new function
def multiplier(factor):
result = constant_factor * factor
return result
# Return the FUNCTION, not a number
return multiplier
doubler = multiplier_factory(2)
tripler = multiplier_factory(3)
print (doubler(1)) # prints 2
print (tripler(1)) # prints 3
print (doubler('a')) # prints 'aa'
print (tripler('a')) # prints 'aaa'
lambda a: a * n is the same of:
def somefunction(a):
return a * n
When you called myfunc(2) you dynamically created a function that is the same of:
def somefunction(a):
return a * 2
myfunc returns a function. So mydoubler is a function and is described by lamda a : a * 2. Then you call that function with the argument 22 and so naturally 11 * 2 = 22 is printed. Lambda functions are not per se recursive, they are just a shorter way of writing a simple function. In your case you can also write:
def myfunc(n):
def multiplier(a):
return a * n
return multiplier

How to change a variable inside a function scope after defining the function in Python?

I'm looking for a way to change the variables defined inside a function after defining the function.
For example
def GetNthPower(x) :
n = None
return x**n
my_numbers_list = [11,23,45,56,78,98]
# now if I feel like I need the 4th power of some numbers in the list
GetNthPower.n = 4
for x in my_numbers_list :
print GetNthPower(x)
# If I want 7th power then
GetNthPower.n = 7
This obviously will not work, is there any way to do this?
N.B: I know we can achieve this by setting 'n' as an argument of the function, but I want to do it this way for a particular reason.
I want my function to have only one argument (for using the function in multiprocessing.Pool.map()).
You can define static variables inside functions, almost like you did:
def GetNthPower(x) :
return x ** GetNthPower.n
GetNthPower.n = 3
print(GetNthPower(2)) #8
Make sure to initialize correctly your GetNthPower.n before first use though.
If you're worried about initialization, you could go for this version which uses a default value 1:
def GetNthPower(x) :
return x ** (GetNthPower.n if hasattr(GetNthPower, "n") else 1)
I think it would still be better for you to write a function that takes two arguments, or use the predefined ** operator.
Don't use one function; create a function that makes your function, using a closure.
def nth_power_maker(n):
def _(x):
return x ** n
return _
my_numbers_list = [11,23,45,56,78,98]
# now if I feel like I need the 4th power of some numbers in the list
get_4th_power = nth_power_maker(4)
for x in my_numbers_list:
print(get_4th_power(x))
get_7th_power = nth_power_maker(7)
Alternatively, you could use functools.partial to bind a keyword argument to a function
from functools import partial
def get_nth_power(x, n):
return x ** n
get_third = partial(get_nth_power, n=3)
get_third(4)
64
x = 4
# in a loop
for pow in [2, 4, 6, 8]:
f = partial(get_nth_power, n=pow)
f(x)

function addFunc at 0x10fae4f28

import math
x = 4
firstFunc = (3 * x) -5
secFunc = 4 - math.pow(2, x)
print(firstFunc, secFunc)
def addFunc(x=4):
result = firstFunc + secFunc
print(result)
print(addFunc)
I'm doing math homework so I decided to add two of these functions by defining a function parameter as x = 4. But unfortunately I'm getting this output "function addFunc at 0x10fae4f28"
You need to call the function like so:
print(addFunc())
What you are seeing is where the function is stored in memory after the def statement has executed, since the function is an object

How to write a function as range?

I need to use a function as range but an error appears saying that n was not set:
NameError: name 'n' is not defined
I'm actually learning how to use python and I do not know if the syntax is correct, I just find examples of lists as ranges.
Could someone clear my ideas, give me some suggestions?
[EDIT1] My function z depends on j and f(n).
[EDIT2] I´m usind fibonacci ranges for integrate over a sphere.
The program is something like this:
def f(n):
a, b = 0, 1
for i in range(n):
a, b = b, a+b
return a
def y(n):
return f(n) + some_const
def z(j):
for j in range(0,f(n-1)):
return j*y(n) + j*f(n-1) + j*f(n)
You have
def z(j):
for j in range(0,f(n-1)):
return j*y(n) + j*f(n-1) + j*f(n)
Notice you say this takes something called j while your other functions take n.
Did you mean
def z(n):
for j in range(0,f(n-1)):
return j*y(n) + j*f(n-1) + j*f(n)
When you get an error check the line number it refers to.
Also, consider giving your variables longers names - just single letters get easy to muddle up!
As pointed out by the comment, once this stops giving the error message it might not do what you want.
You first function loops and then returns:
def f(n):
a = something
for i in range(n):
a = a + i
return a
(I presume something is set to, er, something)
Your z function returns as soon as it gets into the loop: perhaps you just want to collect the results and return them?
def z(n):
stuff = []
for j in range(0,f(n-1)):
stuff.append( j*y(n) + j*f(n-1) + j*f(n) )
return stuff
Notice the return is further left - no longer indented inside the for loop.
In fact you could use a list comprehension then:
def z(n):
return [j*y(n) + j*f(n-1) + j*f(n) for j in range(0,f(n-1))]
There are several problems with the snippet that you posted.
It would help if you include the code that calls the functions. It also seems that you should look into local-scope of vars in Python- it does not matter what you call the parameter passed into the function, so you could call the var in the brackets "n" for every function, but it is preferable to give them a meaningful name that indicates what that parameter represents- just useful for others looking at the code, and good practice!
Lastly, using a docstring inside the function makes it very clear what the functions do, and may include a desc. of the params passed (type/class).
def range_sum(n): # instead of f- range_sum seems appropriate
"""
Sums the range of numbers from 0 to n
>>> range_sum(4) # example data
10
"""
# no idea what a is meant to be, unless an accumulator to
# store the total, in which case it must be initialised
accum = 0
for i in range(1, n+1): #iterates from 1 to n
accum = aaccum + i
return a # returns the total
def y(m, const): # use a descriptive func name
"""
Sums the range of numbers from 0 to m and adds const
>>> y(4, 7) # example data
17
"""
return range_sum(m) + const
def z(j, n, m): # pass all the vars you need for the function so they have a value
"""
Something descriptive
>>> z(4, 2, 5) # example data
?
"""
total
for j in range(0,f(n-1)):
total += j*y(m) + j*f(n-1) + j*f(n)
return total
print("First Func, ", range_sum(4))
print("Second Func, ", y(4, 7))
print("Third Func, ", z(4, 2, 5))
Note that the number of arguments passed to each function matches the number expected by the function. It is possible to set defaults, but get the hang of getting this right first.
Not sure what the last function is meant to do, but as mentioned in the comment above, showing some code to illustrate how you call the code can be useful, as in the sample.

How should I code a function to turn a parameter I input into 1? [duplicate]

This question already has answers here:
How do I pass a variable by reference?
(39 answers)
Closed 8 years ago.
I am the new to Python. Here is a problem that I have encountered.
Assume that there is a function called set1(x).
Here is the code:
def set1(x):
x = 1;
When I run this,
m = 5
set1(m)
m
the value of m is still 5.
So how should I code the function if I want the parameter to become 1 whenever I call the set1() function?
You can return the value
def set1():
return 1;
And call it as
m=5
m = set1()
print (m)
It will print 1
Another way but bad method is to make it global
def set1():
global m
m = 1
Functions use a local namespace in which they declare their variables, which means that in most cases when you pass an argument to a function, it will not effect the argument outside of the function (in the global namespace). So while the value changes within the function, it does not change outside of the function.
If you want the function to change the value, you need to return the value as such:
def set1(x):
x=1
return x
>>> m=5
>>> m = set1(m)
>>> m
1
This said, if your argument is mutable, it can change.
def set2(x):
x[0] = 1
>>> m = [2]
>>> set2(m)
>>> m[0]
1

Categories

Resources