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?
That’s because the
balanceobject you modify insideaddInterestis not the same as theamountobject 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:The
idfunction returns the identity of an object, which can be used to test if two object are the same.