Don’t worry, unlock all articles / blogs on PrepInsta by just simply logging in on our website
Sign in with GoogleSign in with Google
Global Variable in Python
February 18, 2021
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.
Syntax :
global myVariable
#global variable
s=“global”
#function to check scope
defscope():
#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
Login/Signup to comment