Scope and User-De Ned Functions: Hugo Bowne-Anderson
Scope and User-De Ned Functions: Hugo Bowne-Anderson
de ned functions
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
Crash course on scope in functions
Not all objects are accessible everywhere in a script
new_val
<hr />----------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-3-3cc6c6de5c5c> in <module>()
<hr />-> 1 new_value
NameError: name 'new_val' is not defined
def square(value):
"""Returns the square of a number."""
new_val = value ** 2
return new_val
square(3)
new_val
10
def square(value):
"""Returns the square of a number."""
new_value2 = new_val ** 2
return new_value2
square(3)
100
new_val = 20
square(3)
400
def square(value):
"""Returns the square of a number."""
global new_val
new_val = new_val ** 2
return new_val
square(3)
100
new_val
100
Hugo Bowne-Anderson
Instructor
Nested functions (1)
def outer( ... ):
""" ... """
x = ...
new_x1 = x1 % 2 + 5
new_x2 = x2 % 2 + 5
new_x3 = x3 % 2 + 5
def inner(x):
"""Returns the remainder plus 5 of a value."""
return x % 2 + 5
print(mod2plus5(1, 2, 3))
(6, 5, 6)
def inner(x):
"""Raise x to the power of n."""
raised = x ** n
return raised
return inner
square = raise_val(2)
cube = raise_val(3)
print(square(2), cube(4))
4 64
def inner():
nonlocal n
n = 2
print(n)
inner()
print(n)
outer()
2
2
Enclosing functions
Global
Built-in
Hugo Bowne-Anderson
Instructor
You'll learn:
Writing functions with default arguments
power(9, 2)
81
power(9, 1)
power(9)
# Initialize sum
sum_all = 0
return sum_all
add_all(1, 2)
50
print_all(name="dumbledore", job="headmaster")
job: headmaster
name: dumbledore
Hugo Bowne-Anderson
Instructor
Next exercises:
Generalized functions:
Count occurrences for any column
power(9, 2)
81
power(9)
# Initialize sum
sum_all = 0
return sum_all