Mostly Linux & Python syntax notes and hyperlinks.

Wednesday, April 29, 2015

python: scope error - from Amir Rachum's newbie mistakes, Part 2

Slightly rephrasing the examples in http://blog.amir.rachum.com/blog/2013/07/09/python-common-newbie-mistakes-part-2/: 
>>> bar=42
>>> bar
42
>>> def foo():
...     print bar
...   
>>> foo()
42
>>> def foo():
...     print bar
...     bar=2
...   
>>> bar
42
>>> foo()
Traceback (most recent call last):
  File "< input >", line 1, in
  File "< input >", line 2, in foo
UnboundLocalError: local variable 'bar' referenced before assignment
>>> def foo():
...     global bar
...     print bar
...     bar=14
...   
>>> bar
42
>>> foo()
42
>>> bar
14

No comments:

Post a Comment