Lambda Functions: Hugo Bowne-Anderson
Lambda Functions: Hugo Bowne-Anderson
P Y T H O N D ATA S C I E N C E TO O L B O X ( PA R T 1 )
Hugo Bowne-Anderson
Instructor
Lambda functions
raise_to_power = lambda x, y: x ** y
raise_to_power(2, 3)
print(square_all)
print(list(square_all))
Hugo Bowne-Anderson
Instructor
The oat() function
2.0
float('2.3')
2.3
float('hello')
<hr />---------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-3-d0ce8bccc8b2> in <module>()
<hr />-> 1 float('hi')
ValueError: could not convert string to float: 'hello'
2.0
sqrt(10)
3.1622776601683795
------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-cfb99c64761f> in <module>()
----> 1 sqrt('hello')
<ipython-input-1-939b1a60b413> in sqrt(x)
1 def sqrt(x):
----> 2 return x**(0.5)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'float'
sqrt(4)
2.0
sqrt(10.0)
3.1622776601683795
sqrt('hi')
(1.8369701987210297e-16+3j)
def sqrt(x):
"""Returns the square root of a number."""
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')
-----------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-2-4cf32322fa95> in <module>()
----> 1 sqrt(-2)
<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)
ValueError: x must be non-negative
Hugo Bowne-Anderson
Instructor
Errors and exceptions
def sqrt(x):
try:
return x ** 0.5
except:
print('x must be an int or float')
sqrt(4)
2.0
sqrt('hi')
Hugo Bowne-Anderson
Instructor
What you’ve learned:
Write functions that accept single and multiple arguments
Handle errors