变量为空时发生UnboundLocalError

2024-06-01 02:06:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类似的程序:

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')

但是我继续得到一个UnboundLocalError("local variable 'curpuz' referenced before assignment",),即使这个变量显然是局部的。你知道吗


Tags: txtjsonreaddefopenreqsaypuzzle