Functions

Variable Scope

Scope determines where a variable can be accessed.

Local Variables

Variables created inside a function are local:

def my_function():
    x = 10  # Local variable
    print(x)

my_function()  # Works: 10
print(x)       # Error! x doesn't exist here

Global Variables

Variables created outside functions are global:

message = "Hello"  # Global

def greet():
    print(message)  # Can read global

greet()  # Works: Hello

Modifying Globals

Use

global
keyword to modify a global variable:

count = 0

def increment():
    global count
    count += 1

increment()
print(count)  # 1

Best Practice: Avoid global variables when possible. Use parameters and return values instead.

Visualizer
35
assigned to
35
score

Interactive Visualization

python
Loading...
Output
Run execution to see output...