1
player = 'Taro'
def f():
print(player)
f()
Execution result of 1
Taro
2
player = 'Taro'
def f():
print(player)
player = 'Jiro'
f()
Execution result of 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
Taro is included in the global variable player. I put Jiro in the local variable player. But before declaring the local variable player An error occurs because you are trying to execute print (player).
To improve it You need to declare a local variable before print (player).
3
player = 'Taro'
def f():
player = 'Jiro'
print('local:', player)
f()
print('global:', player)
Execution result of 3
local:Jiro
global:Taro
If you want to rewrite global variables in a function
4
player = 'Taro'
def f():
global player
player = 'Jiro'
print('local:', player)
f()
print('global:', player)
Execution result of 4
local:Jiro
global:Jiro
Recommended Posts