我正在阅读 John Zelle 的《Python 编程 2ed Ch6》。我遇到一个概念问题: 他的示例代码如下:
#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()
用上面的代码
"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"
根据这个想法我尝试了一个test.py
def add(balance, rate):
balance = balance * (1 + rate)
def test():
amount = 1000
rate = 0.5
amount = add(amount, rate)
print(amount)
test()
我认为余额也可以通过新值分配,但结果在我的终端中返回“none”。谁能解释一下它们之间的根本区别是什么? 为什么列表赋值不需要使用 return 来传递值但仍然会被保存,另一方面,我的 test.py 确实需要在函数之后有一个“返回余额”?
最佳答案
您没有在 amount
中获得任何值的原因是您的 add
函数没有返回任何内容。
def add(balance,rate):
return balance*(1+rate)
将返回一个分配给金额
的值。
除此之外,开始的代码是错误的。如果您要在 python 中尝试此代码,您会发现它打印出来:
[1000, 2200, 800, 360]
需要更改为:
def addInterest(balances,rate):
for i in range(len(balances)):
balances[i] = balances[i]*(1+rate)
关于python - python的函数返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16027414/