As I know integers are immutable, how would I go about printing 4 instead of 2?
a = 2
def add(num):
num = 4
print(a)
In Python, variables are just baskets that hold values. If you want a to hold a different value, just put it in. Simple as that.
a = 2 # value
a = 3 # new value
Although the integer 2 is immutable, a is just an object reference to that integer. a itself - the object reference- can be changed to reference any object at any time.
As you have discovered, you can't simply pass a variable to a function and change its value:
def f(a):
a = 4
f(a)
print(a) # still 3
Why still 3? Because in Python objects are passed by * object reference*. This is neither the same as by value, nor is it the same as by reference, in other languages.
The a inside of the function is a different object reference than outside of the function. It's a different namespace. If you want to change the function so that its a is the other, final a, you have to explicitly specify that this is what you want.
def f():
global a # this makes any following references to a refer to the global namespace
a = 4
f()
print (a) # 4
I highly recommend this link for further reading.
def f(a): ` a[0]=5` L=[3] f(L) print(L[0]) - a bit convoluted, but it serves as a decent example.
a. Is that what you are asking? It's not very clear, your question is lacking detail.return numto youraddmethod