As a beginner, in order to cement my knowledge of functions in Python, I’ve prepared this Jupyter notebook First-Class Functions. The code in it is working, but before moving on to closures and decorators I would like you to comment on my code please.
def cube(x):
return x ** 3
cube_two = cube(2) # Call the function, set cube_two to the value returned
print(cube) # It says cube is a function
print(cube_two) # The value stored in cube_two
# <function cube at 0x010E71E0>
# 8
Returned values as list
elements and dict values
:
nums = [4, cube(4), cube(4) / cube(4) ** 0.5] # returned values as list elements
print(nums)
cube_dict = {'two_cubed': cube(2), 'five_cubed': cube(5)} # as dict values
print(cube_dict)
# [4, 64, 8.0]
# {'two_cubed': 8, 'five_cubed': 125}
Setting a variable to the cube()
function:
make_cube = cube # Take out those parentheses
print(cube)
print(make_cube) # make_cube points to the cube() function
# <function cube at 0x010E71E0>
# <function cube at 0x010E71E0>
the variable make_cube
can be used as a function, like so:
print(cube)
print(make_cube(4))
# <function cube at 0x010E71E0>
# 64
map
taking a function (int
) as an argument:
str_nums = ['1', '2', '3']
one, two, three = map(int, str_nums) # similar to [int(n) for n in str_nums] which is pythonic
print(str_nums)
print([one, two, three])
# ['1', '2', '3']
# [1, 2, 3]
reduce
is another example: it applies a function of two arguments cumulatively to the items of an iterable.
from functools import reduce
cumu_diff = reduce(lambda x, y: x - y, [3, 2, 1]) # cumulative difference
print(cumu_diff)
# 0
Creating a map
-like function (well, kind of).
def map_it(func, seq): # func (without parentheses) as an argument
for x in seq:
yield func(x)
str_nums = ['1', '2', '3']
one, two, three = map_it(int, str_nums) # same as map(int, str_nums)
print([one, two, three])
# [1, 2, 3]
Returning a function from another function:
def greet(name):
def print_message():
print("Hello, " + name + "!") # print_message() gets the name from greet()
return print_message # returning the function, not calling it
greet_et = greet('E.T.') # greet_et points to print_message()
print(greet)
print(greet_et)
print(greet_et())
# <function greet at 0x01090C90>
# <function greet.<locals>.print_message at 0x010B36A8>
# Hello, E.T.!
# None
Here's another example.
def make_paragraph(tag):
def wrapper(text):
return '<{0}>{1}</{0}>'.format(tag, text)
return wrapper
para_one = make_paragraph('p')
print(para_one('This is a small paragraph.')) # returns '<p>This is a small paragraph.</p>'
#<p>This is a small paragraph.</p>