In Python, there exist another type of variable known as Free Variable. If a variable is used in a code block but not defined there then it is known as free variable.
If a name is bound in a block, it is a local variable of that block, unless declared as nonlocal. If a name is bound at the module level, it is a global variable. (The variables of the module code block are local and global.) If a variable is used in a code block but not defined there, it is a free variable.
In computer programming, the term free variable refers to variables used in a function that are neither local variables nor parameters of that function.
To delete a variable, it uses keyword “del”.
The following code prints 123:
>>> a = 123
>>> def f():
... print a
...
>>> f()
123
>>>
But the following fails:
>>> a = 123
>>> def f():
... print a
... a = 456
... print a
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local variable 'a' referenced before assignment
>>>
I would have expected this to print:
123
456
What am I missing here?
P.S. I'm using Python 2.6.6 if that matters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With