0
2

More than 3 years have passed since last update.

グローバル変数とローカル変数1

Posted at
1
player = '太郎'

def f():
    print(player)

f()
1の実行結果
太郎
2
player = '太郎'

def f():
    print(player)
    player = '次郎'
f()
2の実行結果
Traceback (most recent call last):
  File "Main.py", line 7, in <module>
    f()
  File "Main.py", line 4, in f
    print(player)
UnboundLocalError: local variable 'player' referenced before assignment

グローバル変数playerには太郎が入っている。
ローカル変数playerには次郎を入れた。
しかし、ローカル変数playerを宣言する前に、
print(player)を実行しようとしている為にエラーとなる。

それを改善する為に、
print(player)の前にローカル変数を宣言する必要がある。

3
player = '太郎'

def f():
    player = '次郎'
    print('local:', player)

f()
print('global:', player)
3の実行結果
local: 次郎
global: 太郎

グローバル変数を関数内で書き換えたい場合は、

4
player = '太郎'

def f():
    global player
    player = '次郎'
    print('local:', player)

f()
print('global:', player)
4の実行結果
local: 次郎
global: 次郎
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2