Python Data Science Toolbox I: Lambda Functions
Python Data Science Toolbox I: Lambda Functions
Python Data Science Toolbox I: Lambda Functions
Lambda functions
Python Data Science Toolbox I
Lambda functions
In [1]: raise_to_power = lambda x, y: x ** y
In [2]: raise_to_power(2, 3)
Out[2]: 8
Python Data Science Toolbox I
Anonymous functions
● Function map takes two arguments: map(func, seq)
● map() applies the function to ALL elements in the
sequence
In [3]: print(square_all)
<map object at 0x103e065c0>
In [4]: print(list(square_all))
[2304, 36, 81, 441, 1]
PYTHON DATA SCIENCE TOOLBOX I
Let’s practice!
PYTHON DATA SCIENCE TOOLBOX I
Introduction to
error handling
Python Data Science Toolbox I
In [2]: float('2.3')
Out[2]: 2.3
In [3]: float('hello')
------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-3-d0ce8bccc8b2> in <module>()
----> 1 float('hi')
ValueError: could not convert string to float: 'hello'
Python Data Science Toolbox I
In [2]: sqrt(4)
Out[2]: 2.0
In [3]: sqrt(10)
Out[3]: 3.1622776601683795
Python Data Science Toolbox I
<ipython-input-1-939b1a60b413> in sqrt(x)
1 def sqrt(x):
----> 2 return x**(0.5)
In [2]: sqrt(4)
Out[2]: 2.0
In [3]: sqrt(10.0)
Out[3]: 3.1622776601683795
In [4]: sqrt('hi')
x must be an int or float
Python Data Science Toolbox I
<ipython-input-1-a7b8126942e3> in sqrt(x)
1 def sqrt(x):
2 if x < 0:
----> 3 raise ValueError('x must be non-negative')
4 try:
5 return x**(0.5)
Let’s practice!
PYTHON DATA SCIENCE TOOLBOX I
Bringing it all
together
Python Data Science Toolbox I
def sqrt(x):
try:
return x ** 0.5
except:
print('x must be an int or float')
In [1]: sqrt(4)
Out[1]: 2.0
In [2]: sqrt('hi')
x must be an int or float
Python Data Science Toolbox I
def sqrt(x):
if x < 0:
raise ValueError('x must be non-negative')
try:
return x ** 0.5
except TypeError:
print('x must be an int or float')
PYTHON DATA SCIENCE TOOLBOX I
Let’s practice!
PYTHON DATA SCIENCE TOOLBOX I
Congratulations!
Python Data Science Toolbox I
Congratulations!