python - python的函数返回

标签 python function return

我正在阅读 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/

相关文章:

python - 如何禁用 Pylint 警告?

javascript - 如何访问 next .then() 中的日期 - 获取 api

c++ - 关于c++虚函数的一个困惑

java - 我正在尝试用 Java 为评估问题编写一个天真的搜索代码,但我不完全确定如何去做

java - 函数在应该返回 boolean 值时却没有返回 boolean 值

python - 使用 py2neo 将 python 连接到 neo4j 时出错

python - 如何解决 conda 代理配置中出现的错误?

python - 与 super() 调用有点困惑

function - 在 void 上下文中使用非 void 函数?

c++ - 如何将二维数组传递和返回给函数