How to declare a Global Variable in Python?

Python Tutorials

Summary: In this tutorial, we will learn how to declare a global variable in Python programming language.

Global variables in Python are those variables which are declared in the global scope outside of any function or class.

To declare a global variable in Python either declare the variable outside of the function and class or use the global keyword inside of the function.

For example, the name and website variable in this python code is declared in the global scope:

name = "Pencil Programmer"    #global variable 1

def setWebsite():
    global website            #global variable 2
    website = ""

print(name)                   #outputs "Pencil Programmer"
print(website)                #outputs ""

However, it is important to note that every variable declared outside of the function is not a global variable.

For instance in this Python code, though the number is declared outside of the function, it is a class variable, not a global variable:

class MyClass:
    number = 5          #class variable
    def square(self):
MyClass().square()      #outpus 25

So for best practice, we should always define global variables outside of the scope of classes and functions in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *