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.

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply