上海交通大学 python程序设计课程PPT Ch7 (1).pptVIP

  • 2
  • 0
  • 约1.39万字
  • 约 68页
  • 2019-09-23 发布于湖北
  • 举报

上海交通大学 python程序设计课程PPT Ch7 (1).ppt

* * * * * End Functions that Modify Parameters Return values are the main way to send information from a function back to the caller. Sometimes, we can communicate back to the caller by making changes to the function parameters. Understanding when and how this is possible requires the mastery of some subtle details about how assignment works and the relationship between actual and formal parameters. Functions that Modify Parameters Suppose you are writing a program that manages bank accounts. One function we would need to do is to accumulate interest on the account. Let’s look at a first-cut at the function. def addInterest(balance, rate): newBalance = balance * (1 + rate) balance = newBalance Functions that Modify Parameters The intent is to set the balance of the account to a new value that includes the interest amount. Let’s write a main program to test this: def test(): amount = 1000 rate = 0.05 addInterest(amount, rate) print amount Functions that Modify Parameters We hope that that the 5% will be added to the amount, returning 1050. test() 1000 What went wrong? Nothing! Functions that Modify Parameters The first two lines of the test function create two local variables called amount and rate which are given the initial values of 1000 and 0.05, respectively. def addInterest(balance, rate): newBalance = balance * (1 + rate) balance = newBalance def test(): amount = 1000 rate = 0.05 addInterest(amount, rate) print amount Functions that Modify Parameters Control then transfers to the addInterest function. The formal parameters balance and rate are assigned the values of the actual parameters amount and rate. Even though rate appears in both, they are separate variables (because of scope rules). def addInterest(balance, rate): newBalance = balance * (1 + rate) balance = newBalance def test(): amount = 1000 rate = 0.05 addInterest(amount, rate) print amount Functions that Modify Parameters Th

文档评论(0)

1亿VIP精品文档

相关文档