Global Variable in Python

Global Variable

 

Global variables are defined and declared outside a function.

A global variable can be used anywhere in the program as its scope is the entire program.If the value of a global variable is changed anywhere in the program then the global variable value is changed for the entire program.

Global Variable in Python

Syntax :


global myVariable



#global variable
s=“global”

#function to check scope
def scope():
    #local variable
    x=“local”
    print(“Inside the function”)
    #accessing variables
    print(s)
    print(x)

#calling function
scope()
print(\nOutside the function”)
#accessing variables
print(s)
print(x)


Output :

Inside the function
global
local

Outside the function
global
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
---> 16 print(x)
NameError: name 'x' is not defined