Python函数参数值传递

Python的函数参数是通过值传递的,但是如果变量是可变对象,返回到调用程序后,该对象会呈现被修改后的状态

测试程序如下:

# 值传递不改变变量
def addInterest(balance, rate):
    newBalance = balance * (1+rate)
    return newBalance
def test():
    amount = 1000
    rate = 0.5
    addInterest(amount, rate)
    print(amount)

test()
运行结果如下:

Connected to pydev debugger (build 143.1559)
1000

Process finished with exit code 0
可以发现没有改变变量amount的值,

但是我们如果传递的是列表对象,测试程序如下:

# 传递列表变量,会改变列表的值
def addInterest(balances, rate):
    for i in range(len(balances)):
        balances[i] = balances[i] * (1+rate)
def test():
    amounts = [1000, 105, 45, 739]
    rate = 0.05
    addInterest(amounts, rate)
    print(amounts)

test()
运行结果如下:

Connected to pydev debugger (build 143.1559)
[1050.0, 110.25, 47.25, 775.95]

Process finished with exit code 0

我们会发现函数操作改变了列表对象的值



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值