0% found this document useful (0 votes)
36 views

Scope and User-De Ned Functions: Hugo Bowne-Anderson

The document discusses scope in Python functions. It explains that not all objects are accessible everywhere in a script due to scope. There are global, local, and built-in scopes. Local scope refers to objects defined inside a function, while global scope refers to objects defined in the main body of a script. The document uses examples to illustrate the differences between global and local scopes in functions. It also covers topics like nested functions, returning functions, and using nonlocal to modify variables in an enclosing scope.

Uploaded by

saw
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Scope and User-De Ned Functions: Hugo Bowne-Anderson

The document discusses scope in Python functions. It explains that not all objects are accessible everywhere in a script due to scope. There are global, local, and built-in scopes. Local scope refers to objects defined inside a function, while global scope refers to objects defined in the main body of a script. The document uses examples to illustrate the differences between global and local scopes in functions. It also covers topics like nested functions, returning functions, and using nonlocal to modify variables in an enclosing scope.

Uploaded by

saw
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Scope and user-

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

Scope - part of the program where an object or name may be


accessible
Global scope - de ned in the main body of a script

Local scope - de ned inside a function

Built-in scope - names in the pre-de ned built-ins module

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Global vs. local scope (1)
def square(value):
"""Returns the square of a number."""
new_val = value ** 2
return new_val
square(3)

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

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Global vs. local scope (2)
new_val = 10

def square(value):
"""Returns the square of a number."""
new_val = value ** 2
return new_val
square(3)

new_val

10

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Global vs. local scope (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

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Global vs. local scope (4)
new_val = 10

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

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Let's practice!
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 )
Nested 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
Nested functions (1)
def outer( ... ):
""" ... """
x = ...

def inner( ... ):


""" ... """
y = x ** 2
return ...

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Nested functions (2)
def mod2plus5(x1, x2, x3):
"""Returns the remainder plus 5 of three values."""

new_x1 = x1 % 2 + 5
new_x2 = x2 % 2 + 5
new_x3 = x3 % 2 + 5

return (new_x1, new_x2, new_x3)

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Nested functions (3)
def mod2plus5(x1, x2, x3):
"""Returns the remainder plus 5 of three values."""

def inner(x):
"""Returns the remainder plus 5 of a value."""
return x % 2 + 5

return (inner(x1), inner(x2), inner(x3))

print(mod2plus5(1, 2, 3))

(6, 5, 6)

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Returning functions
def raise_val(n):
"""Return the inner function."""

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

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Using nonlocal
def outer():
"""Prints the value of n."""
n = 1

def inner():
nonlocal n
n = 2
print(n)

inner()
print(n)

outer()

2
2

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Scopes searched
Local scope

Enclosing functions

Global

Built-in

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Let's practice!
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 )
Default and exible
arguments
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
You'll learn:
Writing functions with default arguments

Using exible arguments


Pass any number of arguments to a functions

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Add a default argument
def power(number, pow=1):
"""Raise number to the power of pow."""
new_value = number ** pow
return new_value

power(9, 2)

81

power(9, 1)

power(9)

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Flexible arguments: *args (1)
def add_all(*args):
"""Sum all values in *args together."""

# Initialize sum
sum_all = 0

# Accumulate the sum


for num in args:
sum_all += num

return sum_all

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Flexible arguments: *args (2)
add_all(1)

add_all(1, 2)

add_all(5, 10, 15, 20)

50

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Flexible arguments: **kwargs
print_all(name="Hugo Bowne-Anderson", employer="DataCamp")

name: Hugo Bowne-Anderson


employer: DataCamp

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Flexible arguments: **kwargs
def print_all(**kwargs):
"""Print out key-value pairs in **kwargs."""

# Print out the key-value pairs


for key, value in kwargs.items():
print(key + \": \" + value)

print_all(name="dumbledore", job="headmaster")

job: headmaster
name: dumbledore

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Let's practice!
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 )
Bringing it all
together
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
Next exercises:
Generalized functions:
Count occurrences for any column

Count occurrences for an arbitrary number of columns

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Add a default argument
def power(number, pow=1):
"""Raise number to the power of pow."""
new_value = number ** pow
return new_value

power(9, 2)

81

power(9)

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Flexible arguments: *args (1)
def add_all(*args):
"""Sum all values in *args together."""

# Initialize sum
sum_all = 0

# Accumulate the sum


for num in args:
sum_all = sum_all + num

return sum_all

PYTHON DATA SCIENCE TOOLBOX (PART 1)


Let's practice!
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 )

You might also like