Skip to content

Python global variable in a function | Example code

  • by

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

A 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: Assigning 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 or suggestions on this Python variable function topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading