Global Keyword in Python
Global Keyword
In Python programs, different variables have different scopes. The variable may or may not be accessible inside a function depending on where it is declared. A global keyword is a keyword that allows user 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.
Syntax
global myVariable
Use of Global Keyword
Global keyword is used inside a function only when we want to do assignments or when we want to change a variable. Global is not needed for printing and accessing.
Without Using Global Keyword
#global variables
a=5
b=10
#function to add the variables
def add():
c=a+b
return c
#calling function
print(add())
Output : 15
In the above example we are accessing the global variable, but if we want to assign a new value then we can not do this by declaring the variable globally.
# global variable
myVar = 321
# function to update the variable
def update():
myVar= myVar * 2
print(myVar)
# calling the function
update()
Output : --------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) UnboundLocalError: local variable 'myVar' referenced before assignment
Using Global Keyword
# global variable
myVar = 321
# function to update the variable
def update():
global myVar
myVar= myVar * 2
print(myVar)
# calling the function
update()
Output : 642
Login/Signup to comment