Python Programming: An Introduction to Computer Science

Similar documents
CHAPTER 6 DEFINING FUNCTIONS Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science

Lecture. Defining Functions. Richard E Sarkis CSC 161: The Art of Programming

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science

Introduction to Computer Programming for Non-Majors

Chapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

6. Defining Functions

COSC 1P03. Ch 7 Recursion. Introduction to Data Structures 8.1

CS 111: Program Design I Lecture # 7: First Loop, Web Crawler, Functions

. Written in factored form it is easy to see that the roots are 2, 2, i,

Introduction to Computer Programming for Non-Majors

Computers and Scientific Thinking

Lecture 9: Exam I Review

CS 111: Program Design I Lecture # 7: Web Crawler, Functions; Open Access

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

CS 11 C track: lecture 1

Basic allocator mechanisms The course that gives CMU its Zip! Memory Management II: Dynamic Storage Allocation Mar 6, 2000.

Elementary Educational Computer

COP4020 Programming Languages. Subroutines and Parameter Passing Prof. Robert van Engelen

CSC 220: Computer Organization Unit 11 Basic Computer Organization and Design

Chapter 1. Introduction to Computers and C++ Programming. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

CMPT 125 Assignment 2 Solutions

It just came to me that I 8.2 GRAPHS AND CONVERGENCE

Investigation Monitoring Inventory

Classes and Objects. Again: Distance between points within the first quadrant. José Valente de Oliveira 4-1

Chapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Bezier curves. Figure 2 shows cubic Bezier curves for various control points. In a Bezier curve, only

Recursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle:

CS 111: Program Design I Lecture 20: Web crawling, HTML, Copyright

Code Review Defects. Authors: Mika V. Mäntylä and Casper Lassenius Original version: 4 Sep, 2007 Made available online: 24 April, 2013

Chapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Alpha Individual Solutions MAΘ National Convention 2013

CHAPTER IV: GRAPH THEORY. Section 1: Introduction to Graphs

How do we evaluate algorithms?

CSE 111 Bio: Program Design I Lecture 17: software development, list methods

CSE 111 Bio: Program Design I Class 11: loops

Chapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

9.1. Sequences and Series. Sequences. What you should learn. Why you should learn it. Definition of Sequence

CS 111: Program Design I Lecture 16: Module Review, Encodings, Lists

10/23/18. File class in Java. Scanner reminder. Files. Opening a file for reading. Scanner reminder. File Input and Output

CS 111: Program Design I Lecture 21: Network Analysis. Robert H. Sloan & Richard Warner University of Illinois at Chicago April 10, 2018

Data diverse software fault tolerance techniques

CS : Programming for Non-Majors, Summer 2007 Programming Project #3: Two Little Calculations Due by 12:00pm (noon) Wednesday June

Chapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Appendix D. Controller Implementation

IMP: Superposer Integrated Morphometrics Package Superposition Tool

CS 111: Program Design I Lecture 15: Objects, Pandas, Modules. Robert H. Sloan & Richard Warner University of Illinois at Chicago October 13, 2016

Guide to Applying Online

Counting Regions in the Plane and More 1

Overview Chapter 12 A display model

n Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis

Lecture 1: Introduction and Strassen s Algorithm

Chapter 2. C++ Basics. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13

CSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS)

The Closest Line to a Data Set in the Plane. David Gurney Southeastern Louisiana University Hammond, Louisiana

Lecture 28: Data Link Layer

FURTHER INTEGRATION TECHNIQUES (TRIG, LOG, EXP FUNCTIONS)

One advantage that SONAR has over any other music-sequencing product I ve worked

CS 111 Green: Program Design I Lecture 27: Speed (cont.); parting thoughts

Overview. Chapter 18 Vectors and Arrays. Reminder. vector. Bjarne Stroustrup

Threads and Concurrency in Java: Part 1

Abstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:

Parabolic Path to a Best Best-Fit Line:

Project 2.5 Improved Euler Implementation

Threads and Concurrency in Java: Part 1

Numerical Methods Lecture 6 - Curve Fitting Techniques

Review: The ACID properties

CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19

Software development of components for complex signal analysis on the example of adaptive recursive estimation methods.

Analysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis

Evaluation scheme for Tracking in AMI

Ones Assignment Method for Solving Traveling Salesman Problem

1.2 Binomial Coefficients and Subsets

COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 4. The Processor. Single-Cycle Disadvantages & Advantages

Lecturers: Sanjam Garg and Prasad Raghavendra Feb 21, Midterm 1 Solutions

Arithmetic Sequences

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Pseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance

The Magma Database file formats

Using the Keyboard. Using the Wireless Keyboard. > Using the Keyboard

From last week. Lecture 5. Outline. Principles of programming languages

Getting Started. Getting Started - 1

Weston Anniversary Fund

OCR Statistics 1. Working with data. Section 3: Measures of spread

Polynomial Functions and Models. Learning Objectives. Polynomials. P (x) = a n x n + a n 1 x n a 1 x + a 0, a n 0

Homework 1 Solutions MA 522 Fall 2017

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 3 Classification of FFT Processor Algorithms

Outline and Reading. Analysis of Algorithms. Running Time. Experimental Studies. Limitations of Experiments. Theoretical Analysis

The number n of subintervals times the length h of subintervals gives length of interval (b-a).

CS 111: Program Design I Lecture #26: Heat maps, Nothing, Predictive Policing

Message Integrity and Hash Functions. TELE3119: Week4

% Sun Logo for. X3T10/95-229, Revision 0. April 18, 1998

The isoperimetric problem on the hypercube

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions:

n The C++ template facility provides the ability to define n A generic facility allows code to be written once then

NTH, GEOMETRIC, AND TELESCOPING TEST

Transcription:

Pytho Programmig: A Itroductio to Computer Sciece Chapter 6 Defiig Fuctios Pytho Programmig, 2/e 1

Objectives To uderstad why programmers divide programs up ito sets of cooperatig fuctios. To be able to defie ew fuctios i Pytho. To uderstad the details of fuctio calls ad parameter passig i Pytho. Pytho Programmig, 2/e 2

Objectives (cot.) To write programs that use fuctios to reduce code duplicatio ad icrease program modularity. Pytho Programmig, 2/e 3

The Fuctio of Fuctios So far, we ve see four differet types of fuctios: Our programs comprise a sigle fuctio called mai(). Built-i Pytho fuctios (abs) Fuctios from the stadard libraries (math.sqrt) Fuctios from the graphics module (p.getx()) Pytho Programmig, 2/e 4

The Fuctio of Fuctios Havig similar or idetical code i more tha oe place has some drawbacks. Issue oe: writig the same code twice or more. Issue two: This same code must be maitaied i two separate places. Fuctios ca be used to reduce code duplicatio ad make programs more easily uderstood ad maitaied. Pytho Programmig, 2/e 5

Fuctios, Iformally A fuctio is like a subprogram, a small program iside of a program. The basic idea we write a sequece of statemets ad the give that sequece a ame. We ca the execute this sequece at ay time by referrig to the ame. Pytho Programmig, 2/e 6

Fuctios, Iformally The part of the program that creates a fuctio is called a fuctio defiitio. Whe the fuctio is used i a program, we say the defiitio is called or ivoked. Pytho Programmig, 2/e 7

Fuctios, Iformally Happy Birthday lyrics def mai(): prit("happy birthday to you!" ) prit("happy birthday to you!" ) prit("happy birthday, dear Fred...") prit("happy birthday to you!") Gives us this >>> mai() Happy birthday to you! Happy birthday to you! Happy birthday, dear Fred... Happy birthday to you! Pytho Programmig, 2/e 8

Fuctios, Iformally There s some duplicated code i the program! (prit("happy birthday to you!")) We ca defie a fuctio to prit out this lie: def happy(): prit("happy birthday to you!") With this fuctio, we ca rewrite our program. Pytho Programmig, 2/e 9

Fuctios, Iformally The ew program def sigfred(): happy() happy() prit("happy birthday, dear Fred...") happy() Gives us this output >>> sigfred() Happy birthday to you! Happy birthday to you! Happy birthday, dear Fred... Happy birthday to you! Pytho Programmig, 2/e 10

Fuctios, Iformally Creatig this fuctio saved us a lot of typig! What if it s Lucy s birthday? We could write a ew siglucy fuctio! def siglucy(): happy() happy() prit("happy birthday, dear Lucy...") happy() Pytho Programmig, 2/e 11

Fuctios, Iformally We could write a mai program to sig to both Lucy ad Fred def mai(): sigfred() prit() siglucy() This gives us this ew output >>> mai() Happy birthday to you! Happy birthday to you! Happy birthday, dear Fred.. Happy birthday to you! Happy birthday to you! Happy birthday to you! Happy birthday, dear Lucy... Happy birthday to you! Pytho Programmig, 2/e 12

Fuctios, Iformally This is workig great! But there s still a lot of code duplicatio. The oly differece betwee sigfred ad siglucy is the ame i the third prit statemet. These two routies could be collapsed together by usig a parameter. Pytho Programmig, 2/e 13

Fuctios, Iformally The geeric fuctio sig def sig(perso): happy() happy() prit("happy birthday, dear", perso + ". ) happy() This fuctio uses a parameter amed perso. A paramater is a variable that is iitialized whe the fuctio is called. Pytho Programmig, 2/e 14

Fuctios, Iformally Our ew output >>> sig("fred") Happy birthday to you! Happy birthday to you! Happy birthday, dear Fred. Happy birthday to you! We ca put together a ew mai program! Pytho Programmig, 2/e 15

Fuctios, Iformally Our ew mai program: def mai(): sig("fred") prit() sig("lucy") Gives us this output: >>> mai() Happy birthday to you! Happy birthday to you! Happy birthday, dear Fred. Happy birthday to you! Happy birthday to you! Happy birthday to you! Happy birthday, dear Lucy. Happy birthday to you! Pytho Programmig, 2/e 16

Future Value with a Fuctio I the future value graphig program, we see similar code twice: # Draw bar for iitial pricipal bar = Rectagle(Poit(0, 0), Poit(1, pricipal)) bar.setfill("gree") bar.setwidth(2) bar.draw(wi) bar = Rectagle(Poit(year, 0), Poit(year+1, pricipal)) bar.setfill("gree") bar.setwidth(2) bar.draw(wi) Pytho Programmig, 2/e 17

Future Value with a Fuctio To properly draw the bars, we eed three pieces of iformatio. The year the bar is for How tall the bar should be The widow the bar will be draw i These three values ca be supplied as parameters to the fuctio. Pytho Programmig, 2/e 18

Future Value with a Fuctio The resultig fuctio looks like this: def drawbar(widow, year, height): # Draw a bar i widow startig at year with give height bar = Rectagle(Poit(year, 0), Poit(year+1, height)) bar.setfill("gree") bar.setwidth(2) bar.draw(widow) To use this fuctio, we supply the three values. If wi is a Graphwi, we ca draw a bar for year 0 ad pricipal of $2000 usig this call: drawbar(wi, 0, 2000) Pytho Programmig, 2/e 19

Fuctios ad Parameters: The Details It makes sese to iclude the year ad the pricipal i the drawbar fuctio, but why sed the widow variable? The scope of a variable refers to the places i a program a give variable ca be refereced. Pytho Programmig, 2/e 20

Fuctios ad Parameters: The Details Each fuctio is its ow little subprogram. The variables used iside of a fuctio are local to that fuctio, eve if they happe to have the same ame as variables that appear iside of aother fuctio. The oly way for a fuctio to see a variable from aother fuctio is for that variable to be passed as a parameter. Pytho Programmig, 2/e 21

Fuctios ad Parameters: The Details Sice the GraphWi i the variable wi is created iside of mai, it is ot directly accessible i drawbar. The widow parameter i drawbar gets assiged the value of wi from mai whe drawbar is called. Pytho Programmig, 2/e 22

Fuctios ad Parameters: The Details A fuctio defiitio looks like this: def <ame>(<formal-parameters>): <body> The ame of the fuctio must be a idetifier Formal-parameters is a possibly empty list of variable ames Pytho Programmig, 2/e 23

Fuctios ad Parameters: The Details Formal parameters, like all variables used i the fuctio, are oly accessible i the body of the fuctio. Variables with idetical ames elsewhere i the program are distict from the formal parameters ad variables iside of the fuctio body. Pytho Programmig, 2/e 24

Fuctios ad Parameters: The Details A fuctio is called by usig its ame followed by a list of actual parameters or argumets. <ame>(<actual-parameters>) Whe Pytho comes to a fuctio call, it iitiates a four-step process. Pytho Programmig, 2/e 25

Fuctios ad Parameters: The Details The callig program suspeds executio at the poit of the call. The formal parameters of the fuctio get assiged the values supplied by the actual parameters i the call. The body of the fuctio is executed. Cotrol returs to the poit just after where the fuctio was called. Pytho Programmig, 2/e 26

Fuctios ad Parameters: The Details Let s trace through the followig code: sig("fred") prit() sig("lucy") Whe Pytho gets to sig("fred"), executio of mai is temporarily suspeded. Pytho looks up the defiitio of sig ad sees that it has oe formal parameter, perso. Pytho Programmig, 2/e 27

Fuctios ad Parameters: The Detail The formal parameter is assiged the value of the actual parameter. It s as if the followig statemet had bee executed: perso = "Fred" Pytho Programmig, 2/e 28

Fuctios ad Parameters: The Details Note that the variable perso has just bee iitialized. Pytho Programmig, 2/e 29

Fuctios ad Parameters: The Details At this poit, Pytho begis executig the body of sig. The first statemet is aother fuctio call, to happy. What happes ext? Pytho suspeds the executio of sig ad trasfers cotrol to happy. happy cosists of a sigle prit, which is executed ad cotrol returs to where it left off i sig. Pytho Programmig, 2/e 30

Fuctios ad Parameters: The Details Executio cotiues i this way with two more trips to happy. Whe Pytho gets to the ed of sig, cotrol returs to mai ad cotiues immediately followig the fuctio call. Pytho Programmig, 2/e 31

Fuctios ad Parameters: The Details Notice that the perso variable i sig has disappeared! The memory occupied by local fuctio variables is reclaimed whe the fuctio exits. Local variables do ot retai ay values from oe fuctio executio to the ext. Pytho Programmig, 2/e 32

Fuctios ad Parameters: The Details The ext statemet is the bare prit, which produces a blak lie. Pytho ecouters aother call to sig, ad cotrol trasfers to the sig fuctio, with the formal parameter Lucy. Pytho Programmig, 2/e 33

Fuctios ad Parameters: The Details The body of sig is executed for Lucy with its three side trips to happy ad cotrol returs to mai. Pytho Programmig, 2/e 34

Fuctios ad Parameters: The Details Pytho Programmig, 2/e 35

Fuctios ad Paramters: The Details Oe thig ot addressed i this example was multiple parameters. I this case the formal ad actual parameters are matched up based o positio, e.g. the first actual parameter is assiged to the first formal parameter, the secod actual parameter is assiged to the secod formal parameter, etc. Pytho Programmig, 2/e 36

Fuctios ad Parameters: The Details As a example, cosider the call to drawbar: drawbar(wi, 0, pricipal) Whe cotrol is passed to drawbar, these parameters are matched up to the formal parameters i the fuctio headig: def drawbar(widow, year, height): Pytho Programmig, 2/e 37

Fuctios ad Parameters: The Details The et effect is as if the fuctio body had bee prefaced with three assigmet statemets: widow = wi year = 0 height = pricipal Pytho Programmig, 2/e 38

Gettig Results from a Fuctio Passig parameters provides a mechaism for iitializig the variables i a fuctio. Parameters act as iputs to a fuctio. We ca call a fuctio may times ad get differet results by chagig its parameters. Pytho Programmig, 2/e 39

Fuctios That Retur Values We ve already see umerous examples of fuctios that retur values to the caller. discrt = math.sqrt(b*b 4*a*c) The value b*b 4*a*c is the actual parameter of math.sqrt. We say sqrt returs the square root of its argumet. Pytho Programmig, 2/e 40

Fuctios That Retur Values This fuctio returs the square of a umber: def square(x): retur x*x Whe Pytho ecouters retur, it exits the fuctio ad returs cotrol to the poit where the fuctio was called. I additio, the value(s) provided i the retur statemet are set back to the caller as a expressio result. Pytho Programmig, 2/e 41

Fuctios That Retur Values >>> square(3) 9 >>> prit(square(4)) 16 >>> x = 5 >>> y = square(x) >>> prit(y) 25 >>> prit(square(x) + square(3)) 34 Pytho Programmig, 2/e 42

Fuctios That Retur Values We ca use the square fuctio to write a routie to calculate the distace betwee (x 1,y 1 ) ad (x 2,y 2 ). def distace(p1, p2): dist = math.sqrt(square(p2.getx() - p1.getx()) + square(p2.gety() - p1.gety())) retur dist Pytho Programmig, 2/e 43

Fuctios That Retur Values Sometimes a fuctio eeds to retur more tha oe value. To do this, simply list more tha oe expressio i the retur statemet. def sumdiff(x, y): sum = x + y diff = x y retur sum, diff Pytho Programmig, 2/e 44

Fuctios That Retur Values Whe callig this fuctio, use simultaeous assigmet. um1, um2 = eval(iput("eter two umbers (um1, um2) ")) s, d = sumdiff(um1, um2) prit("the sum is", s, "ad the differece is", d) As before, the values are assiged based o positio, so s gets the first value retured (the sum), ad d gets the secod (the differece). Pytho Programmig, 2/e 45

Fuctios That Retur Values Oe gotcha all Pytho fuctios retur a value, whether they cotai a retur statemet or ot. Fuctios without a retur had back a special object, deoted Noe. A commo problem is writig a valuereturig fuctio ad omittig the retur! Pytho Programmig, 2/e 46

Fuctios That Retur Values If your value-returig fuctios produce strage messages, check to make sure you remembered to iclude the retur! Pytho Programmig, 2/e 47

Fuctios that Modify Parameters Retur values are the mai way to sed iformatio from a fuctio back to the caller. Sometimes, we ca commuicate back to the caller by makig chages to the fuctio parameters. Uderstadig whe ad how this is possible requires the mastery of some subtle details about how assigmet works ad the relatioship betwee actual ad formal parameters. Pytho Programmig, 2/e 48

Fuctios that Modify Parameters Suppose you are writig a program that maages bak accouts. Oe fuctio we would eed to do is to accumulate iterest o the accout. Let s look at a first-cut at the fuctio. def additerest(balace, rate): ewbalace = balace * (1 + rate) balace = ewbalace Pytho Programmig, 2/e 49

Fuctios that Modify Parameters The itet is to set the balace of the accout to a ew value that icludes the iterest amout. Let s write a mai program to test this: def test(): amout = 1000 rate = 0.05 additerest(amout, rate) prit(amout) Pytho Programmig, 2/e 50

Fuctios that Modify Parameters We hope that that the 5% will be added to the amout, returig 1050. >>> test() 1000 What wet wrog? Nothig! Pytho Programmig, 2/e 51

Fuctios that Modify Parameters The first two lies of the test fuctio create two local variables called amout ad rate which are give the iitial values of 1000 ad 0.05, respectively. def additerest(balace, rate): ewbalace = balace * (1 + rate) balace = ewbalace def test(): amout = 1000 rate = 0.05 additerest(amout, rate) prit(amout) Pytho Programmig, 2/e 52

Fuctios that Modify Parameters Cotrol the trasfers to the additerest fuctio. The formal parameters balace ad rate are assiged the values of the actual parameters amout ad rate. Eve though rate appears i both, they are separate variables (because of scope rules). def additerest(balace, rate): ewbalace = balace * (1 + rate) balace = ewbalace def test(): amout = 1000 rate = 0.05 additerest(amout, rate) prit(amout) Pytho Programmig, 2/e 53

Fuctios that Modify Parameters The assigmet of the parameters causes the variables balace ad rate i additerest to refer to the values of the actual parameters! def additerest(balace, rate): ewbalace = balace*(1 + rate) balace = ewbalace def test(): amout = 1000 rate = 0.05 additerest(amout, rate) prit(amout) Pytho Programmig, 2/e 54

Fuctios that Modify Parameters Pytho Programmig, 2/e 55

Fuctios that Modify Parameters Executig the first lie of additerest creates a ew variable, ewbalace. balace is the assiged the value of ewbalace. def additerest(balace, rate): ewbalace = balace * (1 + rate) balace = ewbalace def test(): amout = 1000 rate = 0.05 additerest(amout, rate) prit(amout) Pytho Programmig, 2/e 56

Fuctios that Modify Parameters balace ow refers to the same value as ewbalace, but this had o effect o amout i the test fuctio. def additerest(balace, rate): ewbalace = balace * (1 + rate) balace = ewbalace def test(): amout = 1000 rate = 0.05 additerest(amout, rate) prit (amout) Pytho Programmig, 2/e 57

Fuctios that Modify Parameters Pytho Programmig, 2/e 58

Fuctios that Modify Parameters Executio of additerest has completed ad cotrol returs to test. The local variables, icludig the parameters, i additerest go away, but amout ad rate i the test fuctio still refer to their iitial values! def additerest(balace, rate): ewbalace = balace * (1 + rate) balace = ewbalace def test(): amout = 1000 rate = 0.05 additerest(amout, rate) prit(amout) Pytho Programmig, 2/e 59

Fuctios that Modify Parameters To summarize: the formal parameters of a fuctio oly receive the values of the actual parameters. The fuctio does ot have access to the variable that holds the actual parameter. Pytho is said to pass all parameters by value. Pytho Programmig, 2/e 60

Fuctios that Modify Parameters Some programmig laguages (C++, Ada, ad may more) do allow variables themselves to be set as parameters to a fuctio. This mechaism is said to pass parameters by referece. Whe a ew value is assiged to the formal parameter, the value of the variable i the callig program actually chages. Pytho Programmig, 2/e 61

Fuctios that Modify Parameters Sice Pytho does t have this capability, oe alterative would be to chage the additerest fuctio so that it returs the ewbalace. Pytho Programmig, 2/e 62

Fuctios that Modify Parameters def additerest(balace, rate): ewbalace = balace * (1 + rate) retur ewbalace def test(): amout = 1000 rate = 0.05 amout = additerest(amout, rate) prit(amout) test() Pytho Programmig, 2/e 63

Fuctios that Modify Parameters Istead of lookig at a sigle accout, say we are writig a program for a bak that deals with may accouts. We could store the accout balaces i a list, the add the accrued iterest to each of the balaces i the list. We could update the first balace i the list with code like: balaces[0] = balaces[0] * (1 + rate) Pytho Programmig, 2/e 64

Fuctios that Modify Parameters This code says, multiply the value i the 0 th positio of the list by (1 + rate) ad store the result back ito the 0 th positio of the list. A more geeral way to do this would be with a loop that goes through positios 0, 1,, legth 1. Pytho Programmig, 2/e 65

Fuctios that Modify Parameters # additerest3.py # Illustrates modificatio of a mutable parameter (a list). def additerest(balaces, rate): for i i rage(le(balaces)): balaces[i] = balaces[i] * (1+rate) def test(): amouts = [1000, 2200, 800, 360] rate = 0.05 additerest(amouts, 0.05) prit(amouts) test() Pytho Programmig, 2/e 66

Fuctios that Modify Parameters Remember, our origial code had these values: [1000, 2200, 800, 360] The program returs: [1050.0, 2310.0, 840.0, 378.0] What happeed? Pytho passes parameters by value, but it looks like amouts has bee chaged! Pytho Programmig, 2/e 67

Fuctios that Modify Parameters The first two lies of test create the variables amouts ad rate. The value of the variable amouts is a list object that cotais four it values. def additerest(balaces, rate): for i i rage(le(balaces)): balaces[i] = balaces[i] * (1+rate) def test(): amouts = [1000, 2200, 800, 360] rate = 0.05 additerest(amouts, 0.05) prit(amouts) Pytho Programmig, 2/e 68

Fuctios that Modify Parameters Pytho Programmig, 2/e 69

Fuctios that Modify Parameters Next, additerest executes. The loop goes through each idex i the rage 0, 1,, legth 1 ad updates that value i balaces. def additerest(balaces, rate): for i i rage(le(balaces)): balaces[i] = balaces[i] * (1+rate) def test(): amouts = [1000, 2200, 800, 360] rate = 0.05 additerest(amouts, 0.05) prit(amouts) Pytho Programmig, 2/e 70

Fuctios that Modify Parameters Pytho Programmig, 2/e 71

Fuctios that Modify Parameters I the diagram the old values are left hagig aroud to emphasize that the umbers i the boxes have ot chaged, but the ew values were created ad assiged ito the list. The old values will be destroyed durig garbage collectio. def additerest(balaces, rate): for i i rage(le(balaces)): balaces[i] = balaces[i] * (1+rate) def test(): amouts = [1000, 2200, 800, 360] rate = 0.05 additerest(amouts, 0.05) prit amouts Pytho Programmig, 2/e 72

Fuctios that Modify Parameters Whe additerest termiates, the list stored i amouts ow cotais the ew values. The variable amouts was t chaged (it s still a list), but the state of that list has chaged, ad this chage is visible to the callig program. Pytho Programmig, 2/e 73

Fuctios that Modify Parameters Parameters are always passed by value. However, if the value of the variable is a mutable object (like a list of graphics object), the chages to the state of the object will be visible to the callig program. This situatio is aother example of the aliasig issue discussed i Chapter 4! Pytho Programmig, 2/e 74

Fuctios ad Program Structure So far, fuctios have bee used as a mechaism for reducig code duplicatio. Aother reaso to use fuctios is to make your programs more modular. As the algorithms you desig get icreasigly complex, it gets more ad more difficult to make sese out of the programs. Pytho Programmig, 2/e 75

Fuctios ad Program Structure Oe way to deal with this complexity is to break a algorithm dow ito smaller subprograms, each of which makes sese o its ow. This topic will be discussed i more detail i Chapter 9. Pytho Programmig, 2/e 76

Fuctios ad Program Structure def mai(): # Itroductio prit("this program plots the growth of a 10 year ivestmet.") Text(Poit(-1, 5000), ' 5.0K').draw(wi) Text(Poit(-1, 7500), ' 7.5k').draw(wi) Text(Poit(-1, 10000), '10.0K').draw(wi) # Get pricipal ad iterest rate pricipal = eval(iput("eter the iitial pricipal: ")) apr = eval(iput("eter the aualized iterest rate: ")) # Create a graphics widow with labels o left edge wi = GraphWi("Ivestmet Growth Chart", 320, 240) wi.setbackgroud("white") wi.setcoords(-1.75,-200, 11.5, 10400) Text(Poit(-1, 0), ' 0.0K').draw(wi) Text(Poit(-1, 2500), ' 2.5K').draw(wi) # Draw bar for iitial pricipal drawbar(wi, 0, pricipal) # Draw a bar for each subsequet year for year i rage(1, 11): pricipal = pricipal * (1 + apr) drawbar(wi, year, pricipal) iput("press <Eter> to quit.") wi.close() Pytho Programmig, 2/e 77

Fuctios ad Program Structure We ca make this program more readable by movig the middle eight lies that create the widow where the chart will be draw ito a value returig fuctio. Pytho Programmig, 2/e 78

Fuctios ad Program Structure def createlabeledwidow(): widow = GraphWi("Ivestmet Growth Chart", 320, 240) widow.setbackgroud("white") widow.setcoords(-1.75,-200, 11.5, 10400) Text(Poit(-1, 0), ' 0.0K').draw(widow) Text(Poit(-1, 2500), ' 2.5K').draw(widow) Text(Poit(-1, 5000), ' 5.0K').draw(widow) Text(Poit(-1, 7500), ' 7.5k').draw(widow) Text(Poit(-1, 10000), '10.0K').draw(widow) retur widow def mai(): prit("this program plots the growth of a 10 year ivestmet.") pricipal = eval(iput("eter the iitial pricipal: ")) apr = eval(iput("eter the aualized iterest rate: ")) wi = createlabeledwidow() drawbar(wi, 0, pricipal) for year i rage(1, 11): pricipal = pricipal * (1 + apr) drawbar(wi, year, pricipal) iput("press <Eter> to quit.") wi.close() Pytho Programmig, 2/e 79