Global and local variables 1

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

Global and local variables 2
Global and local variables 1
Local scope and global scope
Practice applying functions and global variables in Python
Python: Class and instance variables
About Python variables and objects
Python class variables and instance variables
Python variables and object IDs
Declaration of C global variables
Using global variables in python functions
[Python3] Dynamically define global variables in functions
[Python] Use and and or when creating variables
Example of using class variables and class methods
Difference between nonlocal and global in Python
The story of manipulating python global variables
Correlation visualization of features and objective variables