12

所以基本上我不知道这小段代码有什么问题,而且我似乎找不到让它工作的方法。

points = 0

def test():
    addpoint = raw_input ("type ""add"" to add a point")
    if addpoint == "add":
        points = points + 1
    else:
        print "asd"
    return;
test()

我得到的错误是:

UnboundLocalError: local variable 'points' referenced before assignment

注意:我不能将“points = 0”放在函数内部,因为我会重复很多次,所以它总是先将点设置回0。我完全被卡住了,任何帮助将不胜感激!

4

3 回答 3

32

points不在函数的范围内。您可以使用nonlocal获取对变量的引用:

points = 0
def test():
    nonlocal points
    points += 1

如果pointsinsidetest()应该引用最外层(模块)范围,请使用global

points = 0
def test():
    global points
    points += 1
于 2013-09-19T11:34:49.920 回答
7

您还可以将点传递给函数:小例子:

def test(points):
    addpoint = raw_input ("type ""add"" to add a point")
    if addpoint == "add":
        points = points + 1
    else:
        print "asd"
    return points;
if __name__ == '__main__':
    points = 0
    for i in range(10):
        points = test(points)
        print points
于 2013-09-19T11:37:31.687 回答
0

将点移动到测试中:

def test():
    points = 0
    addpoint = raw_input ("type ""add"" to add a point")
    ...

或使用global statement,但这是不好的做法。但更好的方式是它移动指向参数:

def test(points=0):
    addpoint = raw_input ("type ""add"" to add a point")
    ...
于 2013-09-19T11:36:59.710 回答