All coding lessonsLesson 7 of 10

Functions and Scope

Reusable blocks, parameters, return values and namespaces

A function packages behaviour under a name so you can reuse it. Defining a function does not run it; calling it does.

def greet(name):
    """Return a friendly greeting."""
    return f"Hello, {name}!"

message = greet("Ada")
print(message)

The triple-quoted string directly under the def line is the docstring. help(greet) prints it — always write one for anything non-obvious.

Parameters and arguments

def power(base, exponent=2):
    return base ** exponent

print(power(5))              # 25, default exponent
print(power(2, 10))          # positional
print(power(exponent=3, base=2))  # keyword, order free

Flexible signatures

def total(*numbers, **options):
    result = sum(numbers)
    if options.get("double"):
        result *= 2
    return result

print(total(1, 2, 3))              # 6
print(total(1, 2, 3, double=True)) # 12

return ends the function

def classify(n):
    if n < 0:
        return "negative"
    if n == 0:
        return "zero"
    return "positive"

A function without a return statement returns None. Printing and returning are different: print shows text to the user, return hands a value back to the caller.

Scope

counter = 0          # global

def bump():
    counter = 5      # a NEW local variable
    return counter

print(bump(), counter)  # 5 0

Python looks names up in the order Local, Enclosing, Global, Built-in (the LEGB rule). Prefer parameters and return values over global state — it makes functions testable.

A dangerous default

# WRONG: the list is created once and shared between calls
def add(item, bag=[]):
    bag.append(item)
    return bag

# RIGHT
def add(item, bag=None):
    if bag is None:
        bag = []
    bag.append(item)
    return bag
Ask Teacher Smith questions about this Python lessonOpens your AI tutor with a question about “Functions and Scope” →