Python defines a global variable | Example code

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 defines a global variable in Python

Simple example code of 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 and suggestions on this Python variable 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.