← Back to Python Course | Chapter 4: Functions | Lesson 8 of 9

Python Scope & Lifetime

Local Scope

A variable created inside a function exists only in that function's local scope — it's created when the function starts running and destroyed when it returns, invisible to any code outside that function.

Example: Local Scope

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

greet()

Global Scope

Variables assigned at the top level of a script, outside any function, live in the global scope and can be *read* from inside any function without any special syntax — only *reassigning* them requires extra steps.

Example: Global Scope

python
count = 10

def show():
    print(count)

show()

The global Keyword

Attempting to assign to a global variable's name inside a function normally creates a new local variable instead of touching the outer one; declaring it with the global keyword first tells Python you intend to modify the actual outer variable.

Example: The global Keyword

python
count = 0

def increment():
    global count
    count += 1

increment()
print(count)

Nonlocal Scope

In a function nested inside another function, nonlocal lets the inner function modify a variable belonging to the enclosing (but not global) function's scope — distinct from global, which only reaches all the way out to module level.

Example: Nonlocal Scope

python
def outer():
    value = 1
    def inner():
        nonlocal value
        value += 1
    inner()
    print(value)

outer()

Built-in Scope

Built-in names like print(), len(), and int() live in Python's built-in scope, the outermost layer checked last, which is why you can call them from literally anywhere without importing or defining them yourself.

Example: Built-in Scope

python
print(len("hello"))
print(int("42"))

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.