variable

Global vs Local Variable

def F():
	print(x)
def G():
	x=2
	F()
x=1
G()
 
#printed output is 1 not 2

this is because when python runs the function F(), it does not have any local variable named x so it automatically uses the global variable

def F(x):
	print(x)
def G():
    x=2
    F(x)
x=1
G()

this prints 2 because now x is a local variable for F()

Unless we define a variable beforehand, we cant directly use it inside our code. for instance

def G():
	x+=2

gives an error. we can only do this by using the global keyword

global keyword tells python to use the global variable while on the other hand, nonlocal keyword tells it to use the variable defined in the enclosing function, which is not necessarily global

def add(x,L=[]):
	L.append(x)
	return L
a= add(1)
b= add(2)
c= add(3,[])
print(a,b,c)

output is [1,2],[1,2],[3]
In Python, default arguments are evaluated only once when the function is defined, not every time the function is called.

When Python parses def add(x, L=[]):, it creates a single, empty list object in memory and binds it as the default parameter for L. Every future call to add() that doesn’t provide its own list will share and mutate that exact same list object.

Aliasing in Functions

def update(x):
	x=x+2
	print(x)
	return x
x=6
update(x)
print(x)

output- 8 6
This is because x was only aliasing the global value. And since its an immutable object, it pointed somewhere else. Here the x in the function and the x defined are not the same thing

here if x was a mutable object like a list, the editing it would have edited the original list too as it was pointing to that only

to make this more clear, think like this

def update(y):
	y=y+2
	print(y)
	return y

this is the code technically running and there on top x was just an alias and not the actual variable.