5.global and Local Variable
5.global and Local Variable
scope whereas Python local variables are those which are defined inside a function and their
scope is limited to that function only. In other words, we can say that local variables are
accessible only inside the function in which it was initialized whereas the global variables are
accessible throughout the program and inside every function.
def f():
# local variable
s = "I love Geeksforgeeks"
print(s)
# Driver code
f()
Output
I love Geeksforgeeks
Can a local variable be used outside a function?
If we will try to use this local variable outside the function then let’s see what will happen.
def f():
# local variable
s = "I love Geeksforgeeks"
print("Inside Function:", s)
# Driver code
f()
print(s)
Output:
# Global scope
s = "I love Geeksforgeeks"
f()
print("Outside Function", s)
Output
Inside Function I love Geeksforgeeks
Outside Function I love Geeksforgeeks
The variable s is defined as the global variable and is used both inside the function as well as
outside the function.
Note: As there are no locals, the value from the globals will be used but make sure both the
local and the global variables should have same name.
Example
If a variable with the same name is defined inside the scope of the function as well then it will
print the value given inside the function only and not the global value.