关于python:UnboundLocalError当变量显然是本地的

UnboundLocalError when variable is clearly local

本问题已经有最佳答案,请猛点这里访问。

我有一个类似的程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
curpuz = 1

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

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",),即使变量显然是局部的。


试试这个

1
2
def puzzlea(req,arg):
    global curpuz