首页 > 技术文章 > 第一个博客——python通过值传递函数参数

znnby1997 2018-03-11 16:46 原文

功能:银行账户计算利率(python实现)

部分代码:

         def addInterest(balance, rate):

                  newBalance = balance * (1 + rate)

                  balance = newBalance

        

         def test():

                  amount = 1000

                  rate = 0.05

                  addInterest(amount, rate)

                  print(amount)

         test()

问题描述:运行代码后,输出的值并未发生改变。

问题分析:test()函数中,调用addInterest(amount, rate)函数时,创建形式参数amount, rate并将amount赋值为1000,rate赋值为0.05。在执行addInterest()函数时,函数内创建局部变量newBalance,并为其赋值1050,之后将newBalance值赋给形参amount。

         函数addInterest()执行结束后,函数内部局部变量、形式参数被销毁,此时输出的rate只保存了之前的0.05,因此最终输出的值不发生改变。

解决办法:修改函数addInterest(),使其将处理后的变量返回,通过值传递参数:

         def addInterest(balance, rate):

                  newBalance = balance * (1 + rate)

                  return newBalance

推荐阅读