Bringing together the AI community in Singapore – companies, startups, researchers, students, professionals – to collaborate, find research and business opportunities and talent.
- Have an interesting story to share?
- Seeking for AI talent for your organization?
- Seeking research interns for your labs?
- Seeking an industry partner for your AI projects?
- Are you a researcher and seeking an industry partner to do a POC or deployment of your IP/research outcomes?
Python Data Science Toolbox (Part 1)
Do you have any questions relating to Python Data Science Toolbox (Part 1)? Leave them here!
In Chapter 2, there is an example:
"""Return the inner function."""
"""Raise x to the power of n."""
raised = x ** n
In the above codes, Why is "return inner" called without having to pass in the parameter to inner function?
When you returned (or assigned) a function name without any argument like that in Python, you were returning (or assigning) an address to the said function. You did not call the function to perform its instructions. Best illustrated as follows using the provided example:
square_it = raise_val(2) # define a new function to create square values cube_it = raise_val(3) # define a new function to create cube values # now you can use square_it and cube_it just like any other functions print(square_it(3)) # 3**2 = 9 print(square_it(5)) # 5**2 = 25 print(cube_it(3)) # 3**3 = 27 print(cube_it(5)) # 5**3 = 125
Using square_it as an example, by returning the address to the inner function, you are defining dynamically a new function called square_it(x) via raised_val(2). It behaves the same as if you define it directly like this:
def square_it(x): raised = x**2 return raised
Why do we do it? Decorators for one. You can read the following links for more details: