Scope, Defaults, and Mistakes

Functions

Scope, Defaults, and Mistakes

In this tutorial, we'll avoid common function problems with names, scope, and defaults.

Scope means where a variable can be used.

Variables created inside a function are local to that function:

def greet():
    message = "Hello"
    print(message)

greet()
print(message)  # error

message only exists inside greet().

Local Variables

Local variables help keep functions separate. One function's temporary names do not leak into the rest of the program.

def calculate_total(price, quantity):
    total = price * quantity
    return total

total is useful inside the function. Outside, you use the returned value.

Global Variables

A global variable is created outside functions:

tax_rate = 0.2

def add_tax(price):
    return price + (price * tax_rate)

Functions can read global variables, but changing them inside functions can become confusing. Prefer passing values in as parameters.

Default Parameters

A default parameter has a value if no argument is provided:

def greet(name="friend"):
    print("Hello,", name)

greet("Ada")
greet()

Output:

Hello, Ada
Hello, friend

Common Mistake

Do not use a mutable value like a list as a default while learning:

def add_item(item, items=[]):  # risky
    items.append(item)
    return items

Use None instead:

def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

Practice

Create a function with one required parameter and one default parameter, then call it both ways.