Friday 9 August 2013

Sequel... Life and Scope of Local and Global variables in Python programming language

Here is the explanation of how local and global variables behave in Python.

First things first: That puzzle asked here few days back has solution as below:
The output of the python program is a run time error, variable used before initialized:
Traceback (most recent call last):
File "python_local_global_vars.py", line 10, in
test()
File "python_local_global_vars.py", line 5, in test
print "Global", i
UnboundLocalError: local variable 'i' referenced before assignment

Reasoning:
There is a global variable i initialized to 333. Then in the function test() there is a local variable i declared as the for loop counter. In python when there is a variable referenced , it will look for any local variable of that name first, if not found it looks for a global variable of that name. A local variable overrides the global variable if the name of the two is same.But in this example the local variables' life begins only at the statement of the for loop, not any before.
But when we try to print the variable i before that as Global i , in the statement 
print "Global i =", i 
 python sees there is a local variable of same name , so it overrides the global i, but the value of local i is not initialized until the for loop. So we are accessing a uninitialized local variable in that print statement. Hence the python run time error occurs.




No comments: