中級 › UnboundLocalError: cannot access local variable の原因と直し方 › パターン1
UnboundLocalError: cannot access local variable の原因と直し方
関数内で変数に代入すると、Pythonはその変数を自動的にローカル変数とみなします。
1 count = 0 2 3 def increment(): 4 ______________ ^ 5 count = count + 1 6 return count 7 8 print(increment())
Traceback (most recent call last):
File "main.py", line 8, in <module>
print(increment())
^^^^^^^^^^^
File "main.py", line 5, in increment
count = count + 1
^^^^^
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
空欄を埋めて実行を通す
関数内で変数に代入すると、Pythonはその変数を自動的にローカル変数とみなします。グローバル変数を書き換えたい場合はglobal宣言が必要です。
次の問題