This question already has an answer here:
Python <function at 0x> output [duplicate]
(1 answer)
Closed 3 years ago.
def num(num1, num2):
def adder(num):
return (num1 + num2)
return adder()
num(5, 6)
When I type this code in i get the output of < function num..adder at 0x10b83bdd0 >, and I'm not entirely sure what I'm doing wrong. How do I get it to return 11?
num returns a function, so you need to call it:
num(5, 6)(0) # the number you call it with is irrelevant since you never use num in adder
# 11
In this case this approach is kind of useless. This is usually done if you want to define a partial function or a "function factory", for example:
def multiplier(multiply_by):
def inner(n):
return multiply_by * n
return inner
multiply_by_2 = multiplier(2)
multiply_by_4 = multiplier(4)
print(multiply_by_2(4))
print(multiply_by_4(4))
Outputs
8
16
Your example would have made more sense if the argument was actually used in the inner function, then this becomes very similar to my example above but using addition instead of multiplication:
def adder(num1):
def inner(num2):
return num1 + num2
return inner
two_adder = adder(2)
three_adder = adder(3)
print(two_adder(2))
print(three_adder(2))
Outputs
4
5
You return the adder function, but you don't call it.
The function returns another function. If you want a number, you need to call the returned function as well:
f = adder(1, 2)
print(f(4)) # Call the returned f
Although the second call is useless since you never make use of num.
Related
This question already has answers here:
Can you explain closures (as they relate to Python)?
(13 answers)
Closed 2 years ago.
This is the python function from my pluralsight python class:
def raise_to(exp):
def raise_to_exp(x):
return pow(x, exp)
return raise_to_exp
And the instructor now opens an interactive session and does the following:
from raise_to import raise_to
square = raise_to(2), and then goes on to do
square(5)
and that produces the result of 25. How or why pass in two distinct arguments? Now I ran a debug on this code and this is what I observed. When I do this:
def raise_to(exp):
def raise_to_exp(x):
return pow(x, exp)
return raise_to_exp
square = raise_to(2)
print(square)
I get : <function raise_to.<locals>.raise_to_exp at 0x00000246D1A88700>, but if I do as the instructor
def raise_to(exp):
def raise_to_exp(x):
return pow(x, exp)
return raise_to_exp
square = raise_to(2)
print(square(5))
I get 25. I would like to know how this works. I know this is referred as a python factory function but how does it work. Is the function storing the first argument for later use with the second argument passed in?
raise_to_exp is a closure over the parameter exp defined by raise_to. When you call raise_to(2), you get back a function in whose body the variable exp refers to the variable in the scope where raise_to_exp was defined.
This means that square is a function where exp is bound to 2, so roughly equivalent to the definition
def square(x):
return pow(x, 2)
Just to prove that there was no replacement of exp with the value 2, you can do a bit of digging into the function object to change the value of exp.
>>> square(5)
25
>>> square.__closure__[0].cell_contents = 3 # now square is cube!
>>> square(5)
125
def raise_to(exp):
def raise_to_exp(x):
return pow(x, exp)
return raise_to_exp
I made the last statement bold. You're returning a function here. Think of it as
a=lambda x:x+1
a(1)
# 2
When you do
square=raise_to(2)
Now square refers to the function raise_to_exp because raise_to returned the raise_to_exp function. square can be used as a function here.
square(2) # with exp set as 2
# 4
cube=raise_to(3)
cube(2)
# 8
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 2 years ago.
My recrusive function returns None even when I print the variable on the above line
When I call the function it prints exactly what I want, but returns None!
def nRound(vector, root):
tempRoot = root
a = vector.pop()
b = vector.pop()
if a+b < 1.0:
vector.append(a+b)
rootn = Node(a+b)
rootn.right = tempRoot
rootn.left = Node(b)
nRound(vector, rootn)
else:
rootn = Node(a+b)
rootn.right = tempRoot
rootn.left = Node(b)
print(rootn)
return rootn
I don't understand why it returns None instead rootn. Thanks in advance.
Your function is recursive, and only the base case returns a value. Values from the recursive call are not passed upward:
nRound(vector, rootn)
That means an external caller will only get a value if the function immediately reaches the base case. The above line should be
return nRound(vector, rootn)
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 6 months ago.
I know there are several questions about this, I read but I could not understand. I'm trying to use the result of the return of one function in another:
def multiplication(a):
c = a*a
return c
def subtraction(c):
d = c - 2
return d
print(subtraction(c))
Output:
NameError: name 'c' is not defined
I know that there is a possibility of using global variables, but I have seen that this is not a good idea since the variables can change their value.
EDIT:
These two functions are just idiotic examples. I have two functions with words and I need to use the return of the first function in the second function. In case of this my idiotic example, I need the result of the first function (c) in the second function.
You are not calling your functions properly.
def multiplication(a):
c = a*a
return c
def subtraction(c):
d = c - 2
return d
# first store some value in a variable
a = 2
# then pass this variable to your multiplication function
# and store the return value
c = multiplication(a)
# then pass the returned value to your second function and print it
print(subtraction(c))
Does this makes things clearer?
def multiplication(a):
c = a*a
return c
def subtraction(c):
d = c - 2
return d
print(multiplication(5)) # 25
print(subtraction(5)) # 3
print(multiplication(subtraction(5))) # 9
print(subtraction(multiplication(5))) # 23
I think you're trying to do what's happing in the last print statement: first call the multiplication function, and then call the subtraction function on the result.
Note that the variable c in your multiplication function is an entirely different variable from the c in your subtraction function. So much so, that it may make things more clear to rename your variables, perhaps something like this:
def multiplication(a):
product = a * a
return product
def subtraction(a):
difference = a - 2
return difference
So why not use return value?
print(subtraction(multiplication(24)))
?
'c' is not declared outside the 'subtraction' function.
You need to give need to declare 'c' before printing.
Let's say you want 'c' to be 5, then:
c = 5
print(subtraction(c))
You have defined two functions which both return a number.
If you call subtraction(c) you will get the error you see, because there is no c.
If you define a c in scope of the print statmenet
c = 42
print(subtraction(c))
it will be ok.
Try thinking of it like this: each function takes a variable does things to it and returns a number.
e.g.
>>> multiplication(101)
10201
That this happened to be called c isnide the function isn't known outside the function (i.e scope).
You can save the number to a variable
>>> x = multiplication(101)
Then x remembers that value.
Or
>>> c = multiplication(101)
This is not the same c as you have inside the functions.
(And after the question edit):
Decide what value you want to call the first function with, for example 101:
>>> c = multiplication(101)
then use that return to call the next function:
>>>> subtraction(c)
Or just chain them togther:
subtraction( multiplication(101) )
To start the chain you will need to use a string, int or defined variable.
Otherwise you get name not defined errors.
Once a variable is used in a function it goes out of scope when the function ends.
Here is a sample decorator:
def smart_divide(func):
def inner(a,b):
print("I am going to divide",a,"and",b)
if b == 0:
print("Whoops! cannot divide")
return
return func(a,b)
return inner
#smart_divide
def divide(a,b):
return a/b
If func is an object then how do the variables a and b get accessed from it?
Isn't it like trying to to do this?
def func(potato):
print(y, x)
Is there a fundamental concept I am not getting? Is what is happening here part of some pattern in Python or is it a special case situation where a and b know were to look because it is a generator?
Update
New example from another stack exchange answer
def my_shiny_new_decorator(a_function_to_decorate):
def the_wrapper_around_the_original_function():
print("Before the function runs")
a_function_to_decorate()
print("After the function runs")
return the_wrapper_around_the_original_function
def a_stand_alone_function():
print("I am a stand alone function, don't you dare modify me")
Generators the manual way
a_stand_alone_function = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function()
Generators the proper way
#my_shiny_new_decorator
def another_stand_alone_function():
print("Leave me alone")
According to the place where I got the new answer from the 'manual' way and the 'proper way' are the same .
I think this example may have caused me to get stuck as I was trying to extend it to when there were parameters involved.
I now realise that what I was imagining didn't make sense
I thought that the original code I posted was equivalent to this
divide = smart_divide(divide(a,b))
which if executed would look like this
def smart_divide(divide(a,b)):
def inner(a,b):
print("I am going to divide",a,"and",b)
if b == 0:
print("Whoops! cannot divide")
return
return func(a,b)
return inner
But this would cause divide(a,b) to be executed right in the top line
in the new example 'a_stand_alone_function' did not have () on the end. Which means it was treated as an object.
So my idea of it looking like this def smart_divide(divide(a,b)): doesn't make sense because the function won't be treated as an object anymore
This leaves me confused as to how smart_devide get the information passed as a parameter.
smart_divide doesn't get a and b passed into it. It returns a function object (the inner function), and that function gets a and b passed into it.
You can see what's actually happening if you try this:
def smart_divide(func):
print("I am running in smart_divide; func=", func)
def inner(a,b):
print("I am going to divide",a,"and",b)
if b == 0:
print("Whoops! cannot divide")
return
return func(a,b)
print("I am returning from smart_divide")
return inner
print("I am running at top level before declaring divide")
#smart_divide
def divide(a,b):
return a/b
print("The name 'divide' now refers to", divide)
print("I am now going to call the divide function")
divide(1, 2)
This outputs:
I am running at top level before declaring divide
I am running in smart_divide; func= <function divide at 0x108ff2bf8>
I am returning from smart_divide
the name 'divide' now refers to <function smart_divide.<locals>.inner at 0x10565db70>
I am now going to call the divide function
I am going to divide 1 and 2
No, your decorator returns inner as new implementaion for divide. Thus, you first call the function inner when your program executes divide(1, 2) for instance. Calls to divide have always to respect the signature of inner (and divide as in your code).
A function like
def divide(a, b): # signature
return a / b # implementation or body
consists of two parts. The signature describes the parameters, and the implementation what the function does.
Your decorator will only modify the implementation of your function as follows:
def divide(a, b): # signature remains unmodified
print("I am going to divide",a,"and",b) # implementation of inner
if b == 0:
print("Whoops! cannot divide")
return
return a / b # call to the original implementation of divide
The name and the signature of divide remains the same. Thus, the signature of inner matters, and not the signature of your decorator.
Im using sum_of_squares to return the sum of the square for each parameter. I am pretty lost with the returning the square for the paramaters.
def sum_of_squares(num1,num2):
return sum(int(c) ** 2 for c in str(num1,num2))
str only takes one argument, you can simply remove it to make the code work.
def sum_of_squares(num1, num2):
return sum(int(c)**2 for c in (num1, num2))
as long as tuck num1 and num2 into an iterable structure.
For this very case, the more proper name is sum_of_two_squares(num1, num2). Using return num1**2+num2**2 is neater for this one.
But for more general function sum_of_squares, we can write it like:
def sum_of_squares(*args):
return sum(int(c)**2 for c in args)