Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #100876
| Newsgroups | comp.lang.python |
|---|---|
| Date | 2015-12-25 19:06 -0800 |
| Message-ID | <d070aa0d-e80f-4efb-a424-351737ddb2fc@googlegroups.com> (permalink) |
| Subject | A newbie quesiton: local variable in a nested funciton |
| From | jfong@ms4.hinet.net |
As a tranditional language programmer like me, the result is really weird.
Here is the test codes in file test1.py:
--------
def outerf():
counter = 55
def innerf():
print(counter)
#counter += 1
return innerf
myf = outerf()
--------
the result is:
--------
>>> import test1
>>> test1.myf()
55
>>>
--------
that's OK. But if I un-comment the line "counter += 1", then it gives me this:
--------
>>> import test1
>>> test1.myf()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\Work\Python34\test1.py", line 41, in innerf
print(counter)
UnboundLocalError: local variable 'counter' referenced before assignment
>>>
--------
In the first situation, the local variable 'counter' can be referenced correctly. But in the second, why a statement added after the print() statement can makes this variable "disappear", even the print() won't do the right thing. Isn't it wired? please help!
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
A newbie quesiton: local variable in a nested funciton jfong@ms4.hinet.net - 2015-12-25 19:06 -0800
Re: A newbie quesiton: local variable in a nested funciton Ben Finney <ben+python@benfinney.id.au> - 2015-12-26 14:41 +1100
Re: A newbie quesiton: local variable in a nested funciton jfong@ms4.hinet.net - 2015-12-26 00:56 -0800
Re: A newbie quesiton: local variable in a nested funciton Ben Finney <ben+python@benfinney.id.au> - 2015-12-26 20:37 +1100
Re: A newbie quesiton: local variable in a nested funciton Chris Angelico <rosuav@gmail.com> - 2015-12-26 14:44 +1100
Re: A newbie quesiton: local variable in a nested funciton jfong@ms4.hinet.net - 2015-12-26 01:07 -0800
Re: A newbie quesiton: local variable in a nested funciton Chris Angelico <rosuav@gmail.com> - 2015-12-26 20:49 +1100
Re: A newbie quesiton: local variable in a nested funciton jfong@ms4.hinet.net - 2015-12-26 20:05 -0800
Re: A newbie quesiton: local variable in a nested funciton jfong@ms4.hinet.net - 2015-12-26 20:11 -0800
Re: A newbie quesiton: local variable in a nested funciton Chris Angelico <rosuav@gmail.com> - 2015-12-27 17:32 +1100
Re: A newbie quesiton: local variable in a nested funciton jfong@ms4.hinet.net - 2015-12-27 17:02 -0800
Re: A newbie quesiton: local variable in a nested funciton Chris Angelico <rosuav@gmail.com> - 2015-12-27 17:22 +1100
csiph-web