python中的函数返回值

2024-09-29 23:15:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了以下代码:

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


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

test()

我预计输出是1050,但仍在打印1000。有人能告诉我我做错了什么吗?你知道吗


Tags: 代码testreturnratedefamountprintbalance
2条回答

函数addInterest()返回值1050,但不应用amount变量的更改,因为您没有作为引用变量传递(我认为python不支持引用变量)。必须将返回值存储到新变量中:

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()

您没有从AddInterest赋值:

amount = addInterest(amount, rate)

相关问题 更多 >

    热门问题