Global Variables
In Python, a variable declared outside of the function or in global scope is known as a global variable. This means the global variables can be accessed inside or outside of the function.
Let’s see an example of how a global variable is created in Python.
Example:1
x = "global" def abc(): print("x inside :", x) #function call abc() print("x outside:", x)
Output:
x inside : global
x outside: global
In the above example variable “x” is a global variable as it is declared in global scope, so its value is present in all the functions of the program.
Example:2
def abc(): print("a inside function :", a) a=500 abc() print("a outside function :", a)
Output:
a inside function : 500
a outside function : 500
>>>
In the above example variable “a” is a global variable as it is declared in global scope, so its value is present in all the functions of the program.
Example:3
a=500 def abc(): print("a in abc() function :", a) def pqr(): print("a in pqr() function :", a) abc() pqr() print("a outside function :", a)
Output:
a in abc() function : 500
a in pqr() function : 500
a outside function : 500
>>>
In the above example variable “a” is a global variable as it is declared in global scope.
so its value is present in all the functions (abc() and pqr() ) of the program.