简体   繁体   English

python中的函数返回值

[英]function return value in python

I wrote the following code: 我写了以下代码:

def addInterest(balance, rate):
    newBalance = balance * (1+rate)
    return newBalance


def test():
    amount=1000
    rate=0.05
    addInterest(amount, rate)
    print("" ,amount)

test()

I expected the output to be 1050, but it is still printing 1000. Can someone tell me what am I doing wrong? 我期望输出为1050,但仍输出1000。有人可以告诉我我做错了什么吗?

您没有从AddInterest分配任何值:

amount = addInterest(amount, rate)

The function addInterest() returns the value 1050, but not apply the changes at amount variable, cos you didn't pass as a referenced variable (i think python doenst support referenced variables). 函数addInterest()返回值1050,但不将更改应用到数量变量,因为您未将cos作为引用变量传递(我认为python doenst支持引用变量)。 You must to store the returned value into a new variable: 您必须将返回的值存储到新变量中:

def addInterest(balance, rate):
    newBalance = balance * (1 + rate)
    return newBalance

def test():
    amount = 1000
    rate = 0.05
    # STORE RETURNED VALUE
    result = addInterest(amount, rate)
    # PRINT RETURNED VALUE
    print(result)

test()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM