Functions · 5 / 27 Theory

Variable scope and documentation

A variable created inside a function only exists inside it. Understanding where each variable lives avoids many mistakes.

Local variables

def calculate():
    result = 42        # local variable
    return result

calculate()
print(result)   # NameError: name 'result' is not defined

Parameters are also local variables. Each time the function is called new ones are created, and they disappear when it ends.

Global variables

A variable created outside any function is global: functions can read it.

VAT = 0.21

def with_vat(price):
    return price * (1 + VAT)

print(with_vat(100))   # 121.0

But if inside the function you assign it a value, you create another local variable with the same name; the global one does not change:

counter = 0

def increment():
    counter = 1        # a different local variable

increment()
print(counter)         # 0

To modify the global one you would have to declare it with global counter, but it is a bad habit. It is much better to pass data through parameters and receive the result with return:

def increment(c):
    return c + 1

counter = 0
counter = increment(counter)
print(counter)   # 1

Functions do not share variables

def a():
    x = 1

def b():
    print(x)   # NameError if b() runs: x only exists inside a()

Documenting a function

A text between triple quotes right below the def line is documentation (a docstring). It explains what the function does, its parameters and what it returns:

def power(base, exponent):
    """Returns base raised to exponent."""
    return base ** exponent

help(power)   # shows that description

Comments with # explain specific lines; the docstring explains the whole function.