Skip to main content

Python Tutorial 5.2 - Variable Scope & Lifetime in Python

Welcome to the “Variable Scope & Lifetime” tutorial!


Overview

Scope determines where a variable is accessible. Lifetime is how long it exists in memory.

Local vs. Global

  • Local variables live inside a function.
  • Global variables live at the module level and can be accessed anywhere.
x = 10  # global

def foo():
    y = 5  # local
    print(x, y)

foo()
print(y)  # NameError!

The global Keyword

count = 0

def increment():
    global count
    count += 1

increment()
print(count)  # 1

Key Takeaways

  • Prefer local variables; use global sparingly.
  • Understand where and how long variables persist.

Happy coding!

Comments