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

points内部test()が最も外側の (モジュール) スコープを参照する必要がある場合は、 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")
    ...

またはグローバルステートメントを使用しますが、それは悪い習慣です。しかし、ポイントをパラメーターに移動するより良い方法:

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