Note from edx.org’s MITx 6.00.1 x
course – lecture 4 functions.
In Python function, each function call
creates a new environment, which scopes bindings of formal parameters and
values and of local variables (those created with assignments within body)
Scoping often called static or lexical
because scope within which variable has value is defined by extent of code
boundaries.
The sample codes are
def f(x):
y=1
x=x+y
return
x
x = 3
y = 2
z = f(x)
what is the variable binding procedure and
what is the output?
these are the initial variables
f is a function
x is 3
y is 2
When z=f(x) is called , python create an
local variable stack as below
x is passed by the paramters. y is the
local variable which is assigned in the first line and it doesn’t have any
relationship with the global y. see below:
After the z=f(x) finishes, the stack and
variables is looking like that
Function local variable x is now set to 4,
but the global variable is still 4, and you get the z as 4.
So at the end of the code, x = 3 , y = 2
Let’s do another test
def f(x):
x=x+t
t
= t+ 1
return
x
x=2
z = f(x)
when the first z = f(2) is called.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
NameError: global name 't' is not defined
Obviously there is an error as t is not defined.
But if we assign t, you will get another
error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local variable 't'
referenced before assignment
Interesting, python knows you have got a ‘t’
but can’t use it.
Now if we assign t first then use the global variable in the
function, let’s see how it goes.
t = 3def f(x):
x=x+t
t = t+ 1
return x
x=2
z = f(x)
at the end of the code, you will get the
variables as:
x=2, t=4 (self increase in the f function)
and z=5 (3+2)
wow. Python can use the global variables in
the function without a global declare. Amazing but some times it is a little
confusing as you may think where we got a variable, isn't it
No comments:
Post a Comment