中級 › UnboundLocalError: cannot access local variable の原因と直し方 › パターン2
UnboundLocalError: cannot access local variable の原因と直し方
関数内で変数に代入すると、Pythonはその変数を自動的にローカル変数とみなします。
1 total = 100 2 3 def add_tax(): 4 ______________ ^ 5 total = total * 1.1 6 return total 7 8 print(add_tax())
Traceback (most recent call last):
File "main.py", line 8, in <module>
print(add_tax())
^^^^^^^^^
File "main.py", line 5, in add_tax
total = total * 1.1
^^^^^
UnboundLocalError: cannot access local variable 'total' where it is not associated with a value
空欄を埋めて実行を通す
代入している行が後にあっても、Pythonは関数全体を先読みしてtotalをローカル変数と判断します。読み込む行が先に実行されるため、その時点でまだ値がありません。
次の問題