本文へスキップ
BecomeCoder

Pythonのエラー · エラー12

UnboundLocalError ― ローカル変数を代入前に使った

関数の中で変数に代入すると、その変数はその関数の中では ローカル変数 扱いになります。代入より前に読もうとすると出ます。同名のグローバル変数があっても区別されず起きるので初心者がよくはまります。

出るコード

count = 0

def increment():
    count += 1   # count はローカル扱いになり、右辺で先に読まれてしまう
    return count

increment()

エラーメッセージ

UnboundLocalError: cannot access local variable 'count' where it is not associated with a value

直し方

関数内でグローバル変数を変更したいなら global count を宣言します。値を渡して返す形にする方が安全です。

def increment(count):
    return count + 1