Python global variable in a function | Example code

Use a global variable within other functions by declaring it as global within each function that assigns a value to it:

Python example global variable in a function

Simple example code uses the global keyword.

glob_var = 0


def set_gvar():
    global glob_var  # Needed to modify global copy of globvar
    glob_var = 100


def display():
    print("Global var", glob_var)  # No need for global declaration to read value of globvar


set_gvar()
display()

Output:

Python global variable in a function

How to access a global variable inside a function in Python?

Answer: Assign a global variable in a function will result in the function creating a new variable with that name even if there’s a global one. ensure to declare an as global in the function before any assignment.

a = 10
def setA(value):
    global a   # declare a to be a global
    a = value  # this sets the global value of a

Do comment if you have any doubts and suggestions on this Python variable function topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.