Global keyword in Python
Global keyword is a keyword that allows a 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. 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.
Rules of global keyword:
Use of global keyword:To access a global variable inside a function there is no need to use global keyword.Example 1:
# Python program showing no need to # use global keyword for accessing # a global value # global variable a =15 b =10 # function to perform addition defadd(): c =a +b print(c) # calling a function add()
If we need to assign a new value to a global variable then we can do that by declaring the variable as global.Code 2: Without global keyword
# Python program showing to modify # a global value without using global # keyword a =15 # function to change a global value defchange(): # increment value of a by 5 a =a +5 print(a) change()
UnboundLocalError: local variable 'a' referenced before assignment
This output is an error because we are trying to assign a value to a variable in an outer scope. This can be done with the use of global variable.Code 3 : With global keyword
❮ Python Keywords
Declare a global variable inside a function, and use it outside the function:
#create a function: def myfunction(): global x x = "hello" #execute the function: myfunction() #x should now be global, and accessible in the global scope. print(x)
Definition and Usage
The global keyword is used to create global variables from a no-global scope, e.g. inside a function.
❮ Python Keywords
For more, checkout Geeks For Geeks and W3Schools.