Skip to content
Codewilds

Lesson 11 of 34 · Functions

Python Scope, Closures and Lambda Functions

medium20 XP3 min read

Where a variable is created decides where it can be used — its scope. Understanding scope explains some of Python's most confusing error messages, and it unlocks a powerful idea: functions are values that can be stored, passed around, created on the fly and even remember things.

Local and global variables

A variable assigned inside a function is local: it exists only while the function runs and is invisible outside. A variable assigned at the top level of a file is global and can be read everywhere:

realm = "Serpent Hollow"   # global


def welcome():
    visitor = "Ada"         # local
    return f"{visitor} enters {realm}"


print(welcome())   # Ada enters Serpent Hollow
print(visitor)     # NameError: name 'visitor' is not defined

The LEGB rule

When Python looks up a name, it searches four scopes in order: Local (the current function), Enclosing (any outer functions), Global (the file) and Built-in (names like print and len). The first match wins — which is why naming a variable sum or list hides the built-in function of the same name.

Assigning to a global variable

Reading a global inside a function is fine, but assigning to a name makes it local to the whole function:

score = 0


def add_point():
    score += 1   # UnboundLocalError: cannot access local variable 'score'


add_point()

You can declare global score inside the function, but code that silently changes globals is hard to follow. The cleaner approach is to pass values in and return new values out: score = add_point(score).

Closures: functions that remember

Functions can be defined inside other functions. The inner function can use the variables of the outer one — and it keeps them even after the outer function has returned. Such a function is called a closure:

def make_greeter(greeting):
    def greet(name):
        return f"{greeting}, {name}!"
    return greet          # return the function itself, without calling it


hello = make_greeter("Hello")
howdy = make_greeter("Howdy")
print(hello("Ada"))   # Hello, Ada!
print(howdy("Bo"))    # Howdy, Bo!

Each call to make_greeter creates a new function with its own remembered greeting.

nonlocal

To reassign a variable of the enclosing function (not just read it), declare it nonlocal:

def make_wallet():
    coins = 0

    def deposit(amount):
        nonlocal coins
        coins += amount
        return coins

    return deposit


deposit = make_wallet()
deposit(5)
print(deposit(10))   # 15

Functions are values

A function name refers to a function object, which you can pass to other functions like any other value:

def apply(func, value):
    return func(value)


print(apply(len, "hiss"))        # 4
print(apply(str.upper, "hiss"))  # HISS

Functions that take or return other functions are called higher-order functions.

Lambda expressions

A lambda creates a small, anonymous function in a single expression. Its result is returned automatically:

double = lambda x: x * 2
print(double(21))                    # 42
print(apply(lambda s: s + "!", "hi")) # hi!

Lambdas shine as short arguments to other functions — for example the key of sorted(), which you'll use with lists in Chapter 3: sorted(words, key=lambda w: w[-1]). If you find yourself giving a lambda a name, a regular def is usually clearer.

Common mistakes

  • UnboundLocalError: assigning to a variable inside a function makes it local everywhere in that function.
  • Shadowing built-ins: after sum = 10, calling sum([1, 2]) fails with TypeError: 'int' object is not callable.
  • Calling instead of returning a function: return greet() returns the result; return greet returns the function.
  • Statements inside a lambda: a lambda holds one expression — no assignments, loops or return.

Assignment

Write three higher-order functions:

  1. make_multiplier(factor) returns a function that takes one number and returns it multiplied by factor.
  2. apply_twice(func, value) calls func on value, then calls func again on that result, and returns the final value.
  3. make_counter() returns a function that takes no arguments and returns 1 on its first call, 2 on the second, 3 on the third, and so on. Each counter keeps its own count.
triple = make_multiplier(3)
triple(5)                           # 15
apply_twice(lambda x: x + 3, 10)    # 16
counter = make_counter()
counter(), counter(), counter()     # 1, 2, 3

Premium lesson

Unlock the full Learn Python course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Scope and closures in other languages

Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.

Lesson last updated on .

Write code ↓
Python+20 XP

Lesson 11 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn Python course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.