Reputation: 17
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 ?
Upvotes: 1
Views: 1004
Reputation: 10489
The reason you are not getting any value in amount
is because your add
function is not returning anything.
def add(balance,rate):
return balance*(1+rate)
Would return a value which would be assigned to amount
.
Added to that, the beginning code is wrong. If you we're to try this code in python you would find that it prints out:
[1000, 2200, 800, 360]
it needs to be changed to:
def addInterest(balances,rate):
for i in range(len(balances)):
balances[i] = balances[i]*(1+rate)
Upvotes: 1
Reputation: 688
As I may expect, if you pass a list as a function argument it like you pass the pointer on this list. Assignment statements in Python do not copy objects, they create bindings between a target and an object. Therefore if you change the list inside the function you can see these changes. If you pass the variables, the copies of these variables are used inside the function.
As an example you can also try this code:
a = [1, 2]
b = a
a.append(3)
print a, b
Output:
[1, 2, 3] [1, 2, 3]
Ups!
Upvotes: 1
Reputation: 298562
Your add
function doesn't return
anything, so Python automatically has it return None
at the end. When you write:
amount = add(amount,rate)
add
returns None
, so amount
is set to None
.
Also, not all objects in Python are mutable, so modifying the variable from inside of the function won't do what you expect. Use return
instead:
def add(balance,rate):
return balance * (1 + rate)
Upvotes: 0