Reputation: 49
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)
Upvotes: 2
Views: 2368
Reputation: 45251
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.
Upvotes: 2
Reputation: 220
Seems like this is what you're trying to achieve:
a = 2
def add():
global a
a = 4
add()
print(a)
The add()
function will change a's value to 4 and the output would be 4.
Upvotes: 0