メインコンテンツまでスキップ

関数での変数

# 関数外に変数を定義
count = 0

def add_count():
count += 1

上記のコードを実行するとどうなるか?

エラーになった


なぜ?

以下の意味は

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

count は関数内で定義されていないよ

というエラー。


どうするか

global を使う

# 関数外に変数を定義
count = 0

def add_count():
global count
count += 1

global を使うと関数外の変数にアクセスできるようになる