In [19]:
# Decomposition
# Abstraction
def sum_func(a, b):
""" docstring
This function returns the sum of two numbers
Input: a, b
Output: a + b
"""
print(a + b)
result = a + b
return result, a, b
a,*b = sum_func(1, 2)
print(a,b)
type(a)
sum_func(1,b=2)
3 3 [1, 2] 3
Out[19]:
(3, 1, 2)
In [6]:
def blank_func():
pass
In [17]:
def is_even(num):
if num % 2 == 0:
return True
else:
return False
is_even(num=2)
Out[17]:
True
In [29]:
# default parameter value
def sum_func(a=1, b=2):
""" docstring
This function returns the sum of two numbers
Input: a, b
Output: a + b
"""
result = a + b
return result
print(sum_func(3,b=2.4))
print(sum_func(3,2.4))
print(sum_func(a=3,b=2.4))
5.4 5.4 5.4
function is variable¶
In [30]:
f1 = sum_func
f1(1,2)
Out[30]:
3
In [33]:
x = -5
abs(x)
float(x)
L = [abs, float]
# [f(x) for f in L]
for f in L:
print(f(x))
5 -5.0
In [36]:
def calculator(x,y,op):
return op(x,y)
def add(x,y):
return x + y
def sub(x,y):
return x - y
calculator(1,2,add)
calculator(1,2,sub)
Out[36]:
-1
In [46]:
# iterable
x = range(5)
for x in x:
print(x)
print(x)
0 1 2 3 4 4
In [48]:
x = range(5)
y = [print(x) for x in x]
0 1 2 3 4
Lambda function¶
In [41]:
x = lambda a,b: a + b
x(1,2)
Out[41]:
3
Variable scope¶
In [43]:
def my_func(x):
a = 5
return x * a
a = 4 # available from the function
my_func(4)
print(a)
4
In [51]:
def my_func(x):
a += 5
return x * a
a = 4 # available from the function
my_func(4)
print(a)
--------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) <ipython-input-51-67f4042c756d> in <cell line: 6>() 4 5 a = 4 # available from the function ----> 6 my_func(4) 7 print(a) <ipython-input-51-67f4042c756d> in my_func(x) 1 def my_func(x): ----> 2 a += 5 3 return x * a 4 5 a = 4 # available from the function UnboundLocalError: local variable 'a' referenced before assignment
In [52]:
L = ['a', 'b', 'c']
def my_func(L):
L.append('d')
my_func(L)
print(L)
['a', 'b', 'c', 'd']
In [56]:
# function that returns function
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(3)
print(mydoubler(11))
print(mydoubler(22))
myfunc(2)(11)
33 66
Out[56]:
22
In [58]:
def make_cylinder_volume_func(r):
def volume(h):
return 3.14 * r * r * h
return volume
volume_func = make_cylinder_volume_func(2)
volume_func(3)
Out[58]:
37.68
In [59]:
type(volume_func)
Out[59]:
function
In [60]:
volume_func
Out[60]:
make_cylinder_volume_func.<locals>.volume
def volume(h)
<no docstring>