X-Received: by 10.140.252.213 with SMTP id x204mr25733290qhc.8.1451099195781; Fri, 25 Dec 2015 19:06:35 -0800 (PST) X-Received: by 10.50.32.10 with SMTP id e10mr708893igi.2.1451099195749; Fri, 25 Dec 2015 19:06:35 -0800 (PST) Path: csiph.com!usenet.blueworldhosting.com!feeder01.blueworldhosting.com!border2.nntp.dca1.giganews.com!nntp.giganews.com!6no863600qgy.0!news-out.google.com!f6ni33892igq.0!nntp.google.com!mv3no21229101igc.0!postnews.google.com!glegroupsg2000goo.googlegroups.com!not-for-mail Newsgroups: comp.lang.python Date: Fri, 25 Dec 2015 19:06:35 -0800 (PST) Complaints-To: groups-abuse@google.com Injection-Info: glegroupsg2000goo.googlegroups.com; posting-host=36.238.104.92; posting-account=G2sM6AoAAADOlDdo9rWD6sFkj3T5ULsz NNTP-Posting-Host: 36.238.104.92 User-Agent: G2/1.0 MIME-Version: 1.0 Message-ID: Subject: A newbie quesiton: local variable in a nested funciton From: jfong@ms4.hinet.net Injection-Date: Sat, 26 Dec 2015 03:06:35 +0000 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable Lines: 38 Xref: csiph.com comp.lang.python:100876 As a tranditional language programmer like me, the result is really weird. Here is the test codes in file test1.py: -------- def outerf(): counter =3D 55 def innerf(): print(counter) #counter +=3D 1 return innerf myf =3D outerf() -------- the result is: -------- >>> import test1 >>> test1.myf() 55 >>> -------- that's OK. But if I un-comment the line "counter +=3D 1", then it gives me = this: -------- >>> import test1 >>> test1.myf() Traceback (most recent call last): File "", line 1, in File "D:\Work\Python34\test1.py", line 41, in innerf print(counter) UnboundLocalError: local variable 'counter' referenced before assignment >>>=20 -------- In the first situation, the local variable 'counter' can be referenced corr= ectly. 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 t= hing. Isn't it wired? please help!