function addFunc at 0x10fae4f28 - python

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

Related

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

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.

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)

Defining a function with another function

Could someone help explain what's going on here? I don't understand what is going on in the third part, and why the result is 9. Thank you!
>>> def square(x):
return x ** 2
>>> def f(x):
return x * x
>>> def try_f(f):
return f(3)
>>> try_f(square)
9
When calling try_f(square) you are passing the square function to try_f.
Inside try_f you named the first argument f: it will have nothing to do with the f() function defined below. This is now a local variable to the current scope of try_f.
As a better example, take this:
def square(x):
return x * x
def double(x):
return x * 2
def try_f(func):
return func(4)
>>> try_f(square)
16
>>> try_f(double)
8
The third function has a function as a parameter so when called it runs the parameter-function with a 3 as a paramater.
try_f(f=square) resolves as square(x=3) which resolves as x*x= 3*3 = 9
you call square function by parameter passing from try_f function and pass 3 as argument to it. You can add print to observe which function is called.
Defining f function doesn't take affect try_f behavour

Why is it considered 'powerful' to pass a function as a parameter?

I am reading through A Concise Introduction to Programming in Python by Mark J.Johnson and I stumbled upon a piece of code that uses darts to estimate the area under the graph. The code is working perfectly fine but I am getting confused as to why you would pass a function as a parameter if you could just call the function anyway.
from random import uniform
from math import exp
def area(function , a ,b ,m ,n = 1000 ): #changed parameter for better understanding
hits = 0
total_area = m * (b-a)
for i in range(n):
x = uniform(a,b)
y = uniform(0,m)
if y <= function(x):
hits += 1
frac = hits / float(n)
return frac * total_area
def f(x):
return exp(-x**2)
def g(x): #new function
return exp(-x**2) + 2
def main():
print area(f,0,2,1)
print area(g,0,2,1)
main()
He states that passing a function as a parameter is 'powerful' but I can't see why?
f is but one graph function. It is not the only function that you could define to create a graph.
You can also define other functions:
def g(x):
return 2 * x ** 2 + x + 5
and pass this into area() without having to alter that function. area() is generic enough to calculate the area of different graph functions, and all you need to do is pass in the graph function to have it calculate that area.
Had you hardcoded f instead of using a parameter, you could no longer do that.
I think the answer should be obvious, especially in this case: You can write a generic function for something like calculus integration that works on any function you pass in. You can modify the function you're integrating by supplying a new function. Likewise for other operations like graphing.

Categories

Resources