How to use a global variable in a Python function


In python, you could use global keyword to declare a variable inside a function as a global variable, such as:

>>> global_var = 0
>>> def fun1():
global_var = 10 # global_var as local var
print(global_var)
>>> def fun2():
global global_var # declare global_var to be a global var
global_var = 5
print(global_var)
>>> print(global_var)
0
>>> fun1()
10
>>> print(global_var)
0
>>> fun2()
5
>>> print(global_var)
5

We define a global_var outside functions. Inside fun1() we define a local global_var without declaring it as global. Although it has the same name as the global_var outside the function, it is totally isolated from the gobal variable--global_var. Inside fun2(), we declare global_var as a global variable, so it becomes global.

 First, we print global_var, it is 0. Then invoke fun1(), it prints the result of the local variable global_var. We then check the value of global_var, it is still 0. Nothing changed. Finally, we invoke fun2(), it changes the global variable--global_var to 5.

Comments

Popular posts from this blog

How to create a memory puzzle game with Python and Pygame (#005)

How to write a slide puzzle game with Python and Pygame (2020 tutorial)

Introduction to multitasking with Python #003 gevent (2020 tutorial)