Global Variables in python are the Variables that are created outside of a function. Global variables can be used anywhere by everyone within the program.
To create a global variable inside a function, you can use the โglobalโ keyword and its scope will be global.
Example-
x=โglobalVariable1โณ #variable declaration
y=โglobalVariable2โณ #variable declaration
def myfunction(): #user function defined
y=โprivateVariableโ #private variable available within myfunction()
global z #keyword global defines global variable in function
z=โglobalVariable3โณ #assigning value to variable
print(x) #access global variable x
print(y) #access private variable y instead of global variable y
print(z) #access to variable declared as global in the function
myfunction() #call to myfunction()
print(x) #access global variable x
print(y) #access global variable y
print(z) #acces of variable outside the function
Output:-
globalVariable1
privateVariable
globalVariable3
globalVariable1
globalVariable2
globalVariable3
Leave a Reply