Scope en zelfgedefinieerde functies

Introductie tot functies in Python

Hugo Bowne-Anderson

Instructor

Spoedcursus scope in functies

  • Niet alle objecten zijn overal in een script toegankelijk

  • Scope: deel van het programma waar een object/naam beschikbaar is

    • Global scope: gedefinieerd in de hoofdbody van een script

    • Local scope: gedefinieerd binnen een functie

    • Built-in scope: namen in de vooraf gedefinieerde built-ins-module

Introductie tot functies 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
Introductie tot functies 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
Introductie tot functies 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
Introductie tot functies 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
Introductie tot functies in Python

Laten we oefenen!

Introductie tot functies in Python

Preparing Video For Download...