简体   繁体   中英

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?

您没有从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). 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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