Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python free variables.Why does this fail?

Tags:

People also ask

Can you free variable in Python?

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.

How do you declare a free variable in Python?

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.

What are free type variables?

In computer programming, the term free variable refers to variables used in a function that are neither local variables nor parameters of that function.

How do you destroy a variable in Python?

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.