Episode 13 of 29

Variable Scope

Understand local vs global scope — where variables are accessible.

Scope determines where a variable is accessible.

Local Scope

def my_func():
    x = 10  # local variable
    print(x)

my_func()  # 10
# print(x) would cause an error

Global Scope

name = "Python"  # global

def greet():
    print("Hello, " + name)

greet()

The global Keyword

count = 0

def increment():
    global count
    count += 1

increment()
print(count)  # 1

Best Practice: Avoid global when possible. Pass values as parameters and return results.