Variable Scope and Returning Values

Variable scope determines where in a program a variable can be accessed. Understanding scope, along with how functions return values, is essential for writing predictable, bug-free code.

The Scope Rules

Python follows the LEGB rule when looking up a variable: Local (inside the current function), Enclosing (inside any outer function, for nested functions), Global (at the top level of the script), and Built-in (Python's predefined names). Python searches in this order until it finds a matching variable name.

x = "global"

def outer():
    x = "enclosing"
    def inner():
        x = "local"
        print(x)   # local
    inner()
    print(x)   # enclosing

outer()
print(x)   # global

Returning Values from Functions

The return statement sends a value back to wherever the function was called, allowing that result to be stored in a variable or used in further calculations. A function without an explicit return statement returns None by default.

def add(a, b):
    return a + b

result = add(5, 7)
print(result)   # 12

A function can also return multiple values at once, which Python packs into a tuple automatically.

def min_max(numbers):
    return min(numbers), max(numbers)

low, high = min_max([4, 9, 1, 7])
Understanding scope prevents a common class of bugs where a variable behaves unexpectedly because it was shadowed by another variable of the same name in a different scope.

Coming Up Next

Next, you'll explore Lambda Functions - a compact way to write small, single-expression functions in Python.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course