Variables assigned outside function definition is called global variable. It can be accessed from outside and inside of the functions. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global. Local variables are accessible inside the function in which it is defined. Trying to access local variable outside function will raise error.
x = 5
y = 6 # global variables
def double():
y = 7 # local variable
print(x*2)
print(y*2)
double_x() # 10
# 14
print(x*2) # 10
print(y*2) # 12
x = 5
y = 6 # global variables
def double():
global y = 7 # changing value of y globally
print(x*2)
print(y*2)
double_x() # 10
# 14
print(x*2) # 10
print(y*2) # 14
Variables defined inside a function is local to that function only. In case of nested functions, if we define a variable as nonlocal, then it’s scope expands to its outer function. Changing a variable as nonlocal in inner function will change the value in outer function.
x = 1
def outer():
x = 5
def inner():
x = 6
print("inner:", x)
inner()
print("outer:", x)
outer()
print("global:", x)
# inner: 6
# outer: 5
# global: 1
Using nonlocal
x = 1
def outer():
x = 5
def inner():
nonlocal x
x = 6
print("inner:", x)
inner()
print("outer:", x)
outer()
print("global:", x)
# inner: 6
# outer: 6
# global: 1
Identifies are the names given by user to represent objects in python like variable, class, function, module etc.