[BangPypers] Python "Wat"s

Anand Chitipothu anandology at gmail.com
Tue Sep 10 07:23:25 CEST 2013


On Tue, Sep 10, 2013 at 10:46 AM, Ramchandra Apte <maniandram01 at gmail.com>wrote:

> I get UnboundLocalError: local variable 'x' referenced before assignment.
> That's strange, I'd expect the first print statement to print 10, not
> generate an exception.
>

A variable is either local or global. It is decided at the compile time. If
there is an assignment to a variable inside a function, it is considered as
local unless it is explicitly declared as global.

This rule doesn't apply to class definitions.

Here is some exercises/puzzles related to scoping rules in Python. I use
these in my advanced python course.

http://anandology.com/apy/slides/scoping-rules.html

Anand


More information about the BangPypers mailing list