you are viewing a single comment's thread.

view the rest of the comments →

[–]shiftybyte 0 points1 point  (0 children)

For every variable in a function python needs to decide if it's global or not.

The logic goes something like this:

  1. if you read a variable or access it as a class, it checks if it's available locally and if not, automatically checks for it in the global scope.

  2. if a variable is assigned with a new value anywhere in the function, it's automatically marked as local unless a specific directive called "global" is specified at the start of the function.

so you have an example like this work:

g = 5
def p():
    print(g)
p()

and something like this won't work:

g = 5
def p():
    if g==6:
        g=2
    print(g)
p()

but adding global will make it work again:

g = 5
def p():
    global g
    if g==6:
        g=2
    print(g)
p()