0

I have a program similar to this:

curpuz = 1

def puzzle(req,_):
    puzzledat = json.loads(open('puzzles.txt','r').read())
    puzzleque = puzzledat[str(curpuz)]['q']
    req.say('Current puzzle: ' + puzzleque + ' - !ans <answer>')

def puzzlea(req,arg):
    puzzledat = json.loads(open('puzzles.txt','r').read())
    puzzleans = puzzledat[str(curpuz)]['a']
    if arg[0] == puzzleans:
        req.say('%tip ' + req.nick + ' 50 -- ' + req.nick + ' got the correct answer! Use !puzzle to get the next puzzle!')
        try:
            puzzledat = json.loads(open('puzzles.txt','r').read())
            curpuz += 1
            puzzleque = puzzledat[str(curpuz)]['q']
            puzzleans = puzzledat[str(curpuz)]['a']
        except:
            req.say("Uh oh no more puzzles :(")
            puzzleans = 'no more'
    else:
        req.reply('Incorrect')

But i continue to get an UnboundLocalError("local variable 'curpuz' referenced before assignment",) even though the variable is clearly local.

TheDoctor
  • 1,450
  • 2
  • 17
  • 28
  • 1
    Yet, it is local, *just not bound*. If it were global you'd get a `NameError` instead. – Martijn Pieters Jun 17 '14 at 15:25
  • `curpz` is not local to `puzzlea`. You can implicitly reference a module-scope variable, as you do in `puzzle()`, but to assign to it as you do in `puzzlea` (`curpuz == 1`), you need to bind it locally within the function, or (as you would likely want here) explicitly mark it global within the function scope. – Silas Ray Jun 17 '14 at 15:28
  • 1
    @SilasRay: It **is** local in `puzzlea` because it is being assigned to. – Martijn Pieters Jun 17 '14 at 15:29
  • @MartijnPieters True enough. I should have said that the module-level variable he means to refer to is not bound locally within the function, so the assignment is done to a local unbound variable with the same name. – Silas Ray Jun 17 '14 at 15:30
  • @SilasRay: second line in the function tries to access the name; that is the source of the `UnboundLocalName` exception: `puzzleans = puzzledat[str(curpuz)]['a']`. – Martijn Pieters Jun 17 '14 at 15:32
  • @MartijnPieters I could have sworn that reading a value from an enclosing scope will work implicitly, but writing to it will fail this way. Maybe I'm confusing this with closures... – Silas Ray Jun 17 '14 at 15:50

1 Answers1

1

try this

def puzzlea(req,arg):
    global curpuz
Rafael Barros
  • 2,738
  • 1
  • 21
  • 28