Skip to content

Python defines a global variable | Example code

  • by

Variables that are created outside of a function are known as global variables in Python. A global variable can be accessed from the whole program.

Example of how to define a global variable in Python

A simple example code creates a global variable and uses it. They can be used inside of functions and outside.

Just declare the variable outside the function or in a global scope.

gv = "Python - Global Variables"


def my_func():
    print(gv)


my_func()

Output:

Python defines a global variable

Do comment if you have any doubts or suggestions on this Python variable 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