中級 › UnboundLocalError: cannot access local variable の原因と直し方 › パターン3
UnboundLocalError: cannot access local variable の原因と直し方
関数内で変数に代入すると、Pythonはその変数を自動的にローカル変数とみなします。
1 flag = False 2 3 def toggle(): 4 _____________ ^ 5 flag = not flag 6 return flag 7 8 print(toggle())
Traceback (most recent call last):
File "main.py", line 8, in <module>
print(toggle())
^^^^^^^^
File "main.py", line 5, in toggle
flag = not flag
^^^^
UnboundLocalError: cannot access local variable 'flag' where it is not associated with a value
空欄を埋めて実行を通す
真偽値の反転のような単純な処理でも同じです。関数の外の変数を書き換えるにはglobal宣言が必要です。
次の問題