I am reading John Zelle's Python programming 2ed Ch6. And I encounter a concept question: His example code says:
#addinterest3.py
def addInterest(balances, rate):
for i in range(len(balances)):
balances[i] * (1 + rate)
def test():
amounts = [1000, 2200, 800, 360]
rate = 0.05
addInterest(amounts, rate)
print(amounts)
test()
with upper code the
"assignments into the list caused it to refer to the new values. The old values will actually get cleaned up when Python does garbage collection"
According to this idea I tried a test.py
def add(balance, rate):
balance = balance * (1 + rate)
def test():
amount = 1000
rate = 0.5
amount = add(amount, rate)
print(amount)
test()
I think the balance can also be assigned by a new values, but it turns out return "none" in my terminal. Can anyone explain what is the fundamental difference between them? Why list assignment dont need to use return to pass the value but will still be saved, on the other hand, my test.py do required a "return balance" after the function ?
addInteresthas no side effects and no explicit return value. Specifically,balances[i]*(1+rate)does not modify any value. Given the code above, this is not correct: "assignments into the list caused it to referto the new values." There are no assignments into the list. That would requirebalances[i] *= (1+rate)