2

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)    
vinwin
  • 49
  • 3
  • Can you explain what's going on in this code example? What's your endgame here? – wbadart Jun 30 '17 at 00:40
  • 2
    Just because the integer itself is immutable, that doesn't stop you assigning a different integer reference to `a`. Is that what you are asking? It's not very clear, your question is lacking detail. – Paul Rooney Jun 30 '17 at 00:40
  • 1
    add a line `return num` to your `add` method – chickity china chinese chicken Jun 30 '17 at 00:44
  • 1
    Function parameters are passed by value, not by reference. You can't change the caller's variable from a function. – Barmar Jun 30 '17 at 00:56
  • 2
    Possible duplicate of [How do I pass a variable by reference?](https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) – Rick Jun 30 '17 at 01:34

2 Answers2

2

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.

Rick
  • 43,029
  • 15
  • 76
  • 119
  • Or process a mutable type: `def f(a):` ` a[0]=5` `L=[3]` `f(L)` `print(L[0])` - a bit convoluted, but it serves as a decent example. – Baldrickk Jun 30 '17 at 01:36
0

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.