Skip to content
Justice Tech School

Global and Local Variables

A variable created outside functions is global. A variable created inside a function is local and disappears when the function ends. To change a global variable from inside a function, declare it with the global keyword, although passing values in and returning results is usually cleaner.

Example
count = 10

def show():
    local = 5
    print(count, local)

show()

def add_one():
    global count
    count = count + 1

add_one()
print(count)

Result

10 5
11

Exercise

Allow a function to change the global count.

def add():
     count
    count += 1

Quiz Test

What happens to a local variable when its function ends?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.