A syntax question

Joel Goldstick joel.goldstick at gmail.com
Mon Nov 10 15:35:47 CET 2014


On Mon, Nov 10, 2014 at 6:39 AM, Wolfgang Maier
<wolfgang.maier at biologie.uni-freiburg.de> wrote:
> You may want to read:
>
> https://docs.python.org/3/faq/programming.html?highlight=global#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value
>
> from the Python docs Programming FAQ section.
> It explains your problem pretty well.
>
> As others have hinted at, always provide concrete Python error messages and
> tracebacks instead of vague descriptions.
>
> Best,
> Wolfgang
>
>
>
> On 11/10/2014 12:07 PM, Mok-Kong Shen wrote:
>>
>>
>> I don't understand the following phenomenon. Could someone kindly
>> explain it? Thanks in advance.
>>
>> M. K. Shen
>>
>> -------------------------------------------------
>>
>> count=5
>>
>> def test():
>>    print(count)
>>    if count==5:
>>      count+=0  ### Error message if this line is active, otherwise ok.
>>      print(count)
>>    return
>>
>> test()
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list

Your problem is that count is not local.  You are reading count from
an outer scope.  When you try to increment count in your function, it
can't because it doesn't exist.
Don't use globals.

-- 
Joel Goldstick
http://joelgoldstick.com



More information about the Python-list mailing list