Global Variables

Also, if you’re inside a function remember to use the global keyword to tell Python that you want to modify the variable in the global scope (see here for more about global vs. local scope).

This modifies the variable in the local scope:

foo = 1234

def do_a_thing():
    foo = 8796

do_a_thing()

print(foo)  # prints 1234

This modifies the variable in the global scope:

foo = 1234

def do_a_thing():
    global foo
    foo = 8796

do_a_thing()

print(foo)  # prints 8796
3 Likes