When does Python evaluate a variable in a function definition

Viewed 1612

I am confused as when does Python evaluates a variable. For example if I do:

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

I get 5, so in the definition of g, the variable p remains unevaluated. It is evaluated when we call g

However if I do:

def make_fun():
    p=5
    def f():
        return p
    return f

f=make_fun()
p=6
print f()

I get 5. Why does notf contains the unevaluated variable p? I would like to have a clear idea as of when precisely the evaluation of variables takes place.

3 Answers
Related