addressalign-toparrow-leftarrow-rightbackbellblockcalendarcameraccwchatcheckchevron-downchevron-leftchevron-rightchevron-small-downchevron-small-leftchevron-small-rightchevron-small-upchevron-upcircle-with-checkcircle-with-crosscircle-with-pluscrosseditemptyheartexportfacebookfolderfullheartglobegmailgoogleimagesinstagramlinklocation-pinmagnifying-glassmailminusmoremuplabelShape 3 + Rectangle 1outlookpersonplusprice-ribbonImported LayersImported LayersImported Layersshieldstartickettrashtriangle-downtriangle-uptwitteruseryahoo

Re: [python-10] Beginner Python Quesiton

From: Jeremy D.
Sent on: Wednesday, December 23, 2009 5:17 PM
Sending again since it apparently never made it through the list.

On Fri, Dec 18, 2009 at 6:35 AM, Jeremy Dunck <[address removed]> wrote:
> On Fri, Dec 18, 2009 at 3:56 AM, Stan Silver <[address removed]> wrote:
>> Hi python programmers,
>> I have a beginner python question I hope someone can help me with. ?I have
>> defined a "sub" function in which I want to increment a local variable in
>> the outer function, but when I run the code, I get this error.
> Firstly, since Python code is whitespace-sensitive­, consider attaching
> a file or using a pastebin (like to share your code.
>> ??File "/Users/stan/Desktop­/", line 94, in tests
>> ?? ?test(dd['one']['two­'] == 12)
>> ??File "/Users/stan/Desktop­/", line 83, in test
>> ?? ?i = i + 1
>> UnboundLocalError: local variable 'i' referenced before assignment
>> Process terminated with an exit code of 1
> When trying to troubleshoot a problem, try to simplify the issue until
> you have a very small amount of code that produces the problem. ?This
> is a general debugging/troublesho­oting tip, and could be used to great
> effect here:
> def tests():
> ?i = 0
> ?def test(aBoolean):
> ? ?i = i + 1
> ?test(True)
> (By the way, see PEP 8 http://www.python...­ for a
> naming guide, but aBoolean here should be named a_boolean).
> All that said, assignment to variables is assumed to be local unless
> declared global. ?You're trying to access a variable i, but you're
> assigning to it without having declared it global.
> See here: http://www.divein...­
> There's a second problem here, which is there is no way (in Python
> 2.x) to assign to a non-local, non-global variable. ?PEP 3104 (which
> made Python 3.0) addresses this with a nonlocal keyword.
> http://www.python...­
> This can be a useful feature, most commonly when you want to have
> closures mutating a namespace only they have access to. ?(
> http://en.wikiped...­) )
> However, the code you posted is just incrementing what I presume is a
> test counter. ?You'd be better off being more explicit. ?Here's a
> revision that might serve better:

Our Sponsors

People in this
Meetup are also in:

Sign up

Meetup members, Log in

By clicking "Sign up" or "Sign up using Facebook", you confirm that you accept our Terms of Service & Privacy Policy