I'm reading a wiki book Python_Programming and I'm a little confused about the piece of code below:
def foo():
def bar():
x=5
return x+y
y=10
return bar()
foo()
well, I notice that y
is defined outside of bar() and it's used in x+y
, which is "before" y
is defined. I think similar code will cause a compiling error in C and we have to write something like:
def foo():
def bar(y):
x=5
return x+y
y=10
return bar(y)
foo()
Without defining y
as a formal parameter in bar()
, I don't think the compiler is OK with it.
But I guess it's totally fine in Python, which is an interpreted language, right?
Is this something different in interpreted language compared to compiled language? What's the actual process Python uses when interpreting the code at top?
EDIT 1: I think the answer below has made this point very clear, it's about free variable and closure. Here are some links which I think help this question a lot:
SO:python-free-variables-why-does-this-fail
SO:closures-in-python