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
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 = "https://pencilprogrammer.com" setWebsite() print(name) #outputs "Pencil Programmer" print(website) #outputs "https://pencilprogrammer.com"
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): print(self.number*self.number) MyClass().square() #outpus 25
So for best practice, we should always define global variables outside of the scope of classes and functions in Python.