Scope and user-defined functions

Introduction to Functions in Python

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 - defined in the main body of a script

    • Local scope - defined inside a function

    • Built-in scope - names in the pre-defined built-ins module

Introduction to Functions in Python

Global vs. local scope (1)

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

square(3)
9
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
Introduction to Functions in Python

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)
9
new_val
10
Introduction to Functions in Python

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(new_val)
400
Introduction to Functions in Python

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
Introduction to Functions in Python

Let's practice!

Introduction to Functions in Python

Preparing Video For Download...