Q:

easy functions with multiple parameters Python 2.7

I'm learning with Zelle's Python Programming and got stuck a little bit on functions. 
We got this: 
def addInterest(balance, rate):
    newBalance = balance * (1+rate)
    balance = newBalance

def test(): 
    amount = 1000
    rate = 0.05
    addInterest(amount, rate)
    print amount

test()

This code fails to print 1050 as output. But the below succeedes:
def addInterest(balance, rate):
    newBalance = balance * (1+rate)
    return newBalance

def test():
    amount = 1000
    rate = 0.05
    amount = addInterest(amount, rate)
    print amount

test() 

The subtle difference lies in the line 3rd of the addInterest function. Zelle explains this but I'm yet to get the hang of it. Can you explain please why the #1 code - being almost idential - does not do what #2 does? 

A:

That's because the balance object you modify inside addInterest is not the same as the amount object you pass to the function. To be short, you modify the local copy of an object, passed to the function, so the value of original object remains intact. You can see it if you run the following code in your python shell:
>>> def addInterest(balance, rate):
...     print (balance)
...     newBalance = balance * (1 + rate)
...     balance = newBalance
... 
>>> amount = 1000
>>> rate = 0.05
>>> print id(amount)
26799216
>>> addInterest(amount, rate)
1000
>>> 

The id function returns the identity of an object, which can be used to test if two object are the same.

