Where Variables Live: Scope

Local variables

A variable created inside a function only exists inside that function. It's called a local variable.

def make_tea():
    cups = 2
    print("Making", cups, "cups")

make_tea()
print(cups)

Output (Python stops with an error)

Making 2 cups
NameError: name 'cups' is not defined

Outside the function, cups doesn't exist, so Python gives a NameError.

Think of it like this: What happens in the kitchen stays in the kitchen. The function is the kitchen; its local variables never leave it – unless you return them.

Global variables

Variables created outside any function are global. Functions can read them:

tax_rate = 0.18

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

print(price_with_tax(100))

Output

118.0

Tip: Pass values into functions with parameters and get them out with return. Functions that only use their parameters are the easiest to understand and test.

Docstrings

A string right under the def line describes what the function does. It's called a docstring, and it's a good habit:

def average(numbers):
    """Return the average of a list of numbers."""
    return sum(numbers) / len(numbers)

print(average([4, 8, 6]))

Output

6.0
HOME LEARN COMMUNITY DASHBOARD