Codzy

Variable scope

A variable's scope is the part of the program where it exists. A variable created inside a function is local: it only exists while the function runs. A variable created outside any function is global.

A function can read a global variable, but to change it, it must declare it with global. In practice, avoid overusing global: it's better to pass arguments and use return.

message = "global"

def show():
    message = "local"
    print(message)

show()
print(message)

counter = 0

def increment():
    global counter
    counter += 1

increment()
increment()
print(counter)

Start the lesson