Global Variable and Keyword in Python

Global Variable and Keyword

 

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.

A global keyword is a keyword that allows users to modify a variable outside of the current scope. It is used to create global variables from a non-global scope i.e inside a function.

Global Variable and Keyword in Python

Syntax :


global myVariable


Example :


#global variable
a=10
b=20

#function 
def update():
    
    #global keyword
    global a
    
    #value global variable a gets changed
    a=100
    #b will behave as a local variable here
    b=200
    
    print(” Inside the function”)
    #accessing variables
    print(a)
    print(b)

#calling function
update()

print(\n Outside the function”)
#accessing variables
print(a)
print(b)


Output :

Inside the function
100
200

Outside the function
100
20