ImageVerifierCode 换一换
格式:PPT , 页数:80 ,大小:724.50KB ,
资源ID:4529556      下载积分:10 金币
快捷下载
登录下载
邮箱/手机:
温馨提示:
快捷下载时,用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)。 如填写123,账号就是123,密码也是123。
特别说明:
请自助下载,系统不会自动发送文件的哦; 如果您已付费,想二次下载,请登录后访问:我的下载记录
支付方式: 支付宝    微信支付   
验证码:   换一换

加入VIP,免费下载
 

温馨提示:由于个人手机设置不同,如果发现不能下载,请复制以下地址【https://www.docduoduo.com/d-4529556.html】到电脑端继续下载(重复下载不扣费)。

已注册用户请登录:
账号:
密码:
验证码:   换一换
  忘记密码?
三方登录: 微信登录   QQ登录   微博登录 

下载须知

1: 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。
2: 试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓。
3: 文件的所有权益归上传用户所有。
4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
5. 本站仅提供交流平台,并不能对任何下载内容负责。
6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

版权提示 | 免责声明

本文(Python+Programming.ppt)为本站会员(hyngb9260)主动上传,道客多多仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知道客多多(发送邮件至docduoduo@163.com或直接QQ联系客服),我们立即给予删除!

Python+Programming.ppt

1、Python Programming, 1/e,1,Python Programming: An Introduction to Computer Science,Python Programming, 1/e,2,Objectives,To understand why programmers divide programs up into sets of cooperating functions. To be able to define new functions in Python. To understand the details of function calls and pa

2、rameter passing in Python.,http:/ 铜球阀 截止阀 蝶阀 http:/ http:/,Python Programming, 1/e,3,Objectives (cont.),To write programs that use functions to reduce code duplication and increase program modularity.,Python Programming, 1/e,4,The Function of Functions,So far, weve seen four different types of funct

3、ions: Our programs comprise a single function called main(). Built-in Python functions (abs) Functions from the standard libraries (math.sqrt) Functions from the graphics module (p.getX(),Python Programming, 1/e,5,The Function of Functions,In the code on page 166, the code for drawing the bars occur

4、s in two different places. The first bar is drawn immediately before the loop. The remaining bars are drawn within the loop.,Python Programming, 1/e,6,The Function of Functions,Having similar or identical code in more than one place has some drawbacks. Issue one: writing the same code twice or more.

5、 Issue two: This same code must be maintained in two separate places. Functions can be used to reduce code duplication and make programs more easily understood and maintained.,Python Programming, 1/e,7,Functions, Informally,A function is like a subprogram, a small program inside of a program. The ba

6、sic idea we write a sequence of statements and then give that sequence a name. We can then execute this sequence at any time by referring to the name.,Python Programming, 1/e,8,Functions, Informally,The part of the program that creates a function is called a function definition. When the function is

7、 used in a program, we say the definition is called or invoked.,Python Programming, 1/e,9,Functions, Informally,Happy Birthday lyrics def main(): print “Happy birthday to you!“ print “Happy birthday to you!“ print “Happy birthday, dear Fred.“ print “Happy birthday to you!“ Gives us this main() Happy

8、 birthday to you! Happy birthday to you! Happy birthday, dear Fred. Happy birthday to you!,Python Programming, 1/e,10,Functions, Informally,Theres some duplicated code in the program! (print “Happy birthday to you!“) We can define a function to print out this line: def happy(): print “Happy birthday

9、 to you!“ With this function, we can rewrite our program.,Python Programming, 1/e,11,Functions, Informally,The new program def singFred(): happy() happy() print “Happy birthday, dear Fred.“ happy() Gives us this output singFred() Happy birthday to you! Happy birthday to you! Happy birthday, dear Fre

10、d. Happy birthday to you!,Python Programming, 1/e,12,Functions, Informally,Creating this function saved us a lot of typing! What if its Lucys birthday? We could write a new singLucy function! def singLucy(): happy() happy() print “Happy birthday, dear Lucy.“ happy(),Python Programming, 1/e,13,Functi

11、ons, Informally,We could write a main program to sing to both Lucy and Fred def main(): singFred() print singLucy() This gives us this new output main() 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

12、birthday, dear Lucy. Happy birthday to you!,Python Programming, 1/e,14,Functions, Informally,This is working great! But theres still a lot of code duplication. The only difference between singFred and singLucy is the name in the third print statement. These two routines could be collapsed together b

13、y using a parameter.,Python Programming, 1/e,15,Functions, Informally,The generic function sing def sing(person): happy() happy() print “Happy birthday, dear“, person + “.“ happy() This function uses a parameter named person. A paramater is a variable that is initialized when the function is called.

14、,Python Programming, 1/e,16,Functions, Informally,Our new output sing(“Fred“) Happy birthday to you! Happy birthday to you! Happy birthday, dear Fred. Happy birthday to you!We can put together a new main program!,Python Programming, 1/e,17,Functions, Informally,Our new main program: def main(): sing

15、(“Fred“) print sing(“Lucy“) Gives us this output: main() 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!,Python Programming, 1/e,18,Future Value with a Func

16、tion,In the future value graphing program, we see similar code twice: # Draw bar for initial principal bar = Rectangle(Point(0, 0), Point(1, principal) bar.setFill(“green“) bar.setWidth(2) bar.draw(win) bar = Rectangle(Point(year, 0), Point(year+1, principal) bar.setFill(“green“) bar.setWidth(2) bar

17、.draw(win),Python Programming, 1/e,19,Future Value with a Function,To properly draw the bars, we need three pieces of information. The year the bar is for How tall the bar should be The window the bar will be drawn in These three values can be supplied as parameters to the function.,Python Programmi

18、ng, 1/e,20,Future Value with a Function,The resulting function looks like this: def drawBar(window, year, height): # Draw a bar in window starting at year with given height bar = Rectangle(Point(year, 0), Point(year+1, height) bar.setFill(“green“) bar.setWidth(2) bar.draw(window) To use this functio

19、n, we supply the three values. If win is a Graphwin, we can draw a bar for year 0 and principal of $2000 using this call: drawBar(win, 0, 2000),Python Programming, 1/e,21,Functions and Parameters: The Details,It makes sense to include the year and the principal in the drawBar function, but why send

20、the window variable? The scope of a variable refers to the places in a program a given variable can be referenced.,Python Programming, 1/e,22,Functions and Parameters: The Details,Each function is its own little subprogram. The variables used inside of one function are local to that function, even i

21、f they happen to have the same name as variables that appear inside of another function. The only way for a function to see a variable from another function is for that variable to be passed as a parameter.,Python Programming, 1/e,23,Functions and Parameters: The Details,Since the GraphWin in the va

22、riable win is created inside of main, it is not directly accessible in drawBar. The window parameter in drawBar gets assigned the value of win from main when drawBar is called.,Python Programming, 1/e,24,Functions and Parameters: The Details,A function definition looks like this: def (): The name of

23、 the function must be an identifier Formal-parameters is a possibly empty list of variable names,Python Programming, 1/e,25,Functions and Parameters: The Details,Formal parameters, like all variables used in the function, are only accessible in the body of the function. Variables with identical name

24、s elsewhere in the program are distinct from the formal parameters and variables inside of the function body.,Python Programming, 1/e,26,Functions and Parameters: The Details,A function is called by using its name followed by a list of actual parameters or arguments. () When Python comes to a functi

25、on call, it initiates a four-step process.,Python Programming, 1/e,27,Functions and Parameters: The Details,The calling program suspends execution at the point of the call. The formal parameters of the function get assigned the values supplied by the actual parameters in the call. The body of the fu

26、nction is executed. Control returns to the point just after where the function was called.,Python Programming, 1/e,28,Functions and Parameters: The Details,Lets trace through the following code: sing(“Fred”) print sing(“Lucy”) When Python gets to sing(“Fred”), execution of main is temporarily suspen

27、ded. Python looks up the definition of sing and sees that it has one formal parameter, person.,Python Programming, 1/e,29,Functions and Parameters: The Detail,The formal parameter is assigned the value of the actual parameter. Its as if the following statement had been executed: person = “Fred”,Pyth

28、on Programming, 1/e,30,Functions and Parameters: The Details,Note that the variable person has just been initialized.,Python Programming, 1/e,31,Functions and Parameters: The Details,At this point, Python begins executing the body of sing. The first statement is another function call, to happy. What

29、 happens next? Python suspends the execution of sing and transfers control to happy. happy consists of a single print, which is executed and control returns to where it left off in sing.,Python Programming, 1/e,32,Functions and Parameters: The Details,Execution continues in this way with two more tr

30、ips to happy. When Python gets to the end of sing, control returns to main and continues immediately following the function call.,Python Programming, 1/e,33,Functions and Parameters: The Details,Notice that the person variable in sing has disappeared! The memory occupied by local function variables

31、is reclaimed when the function exits. Local variables do not retain any values from one function execution to the next.,Python Programming, 1/e,34,Functions and Parameters: The Details,The next statement is the bare print, which produces a blank line. Python encounters another call to sing, and cont

32、rol transfers to the sing function, with the formal parameter “Lucy”.,Python Programming, 1/e,35,Functions and Parameters: The Details,The body of sing is executed for Lucy with its three side trips to happy and control returns to main.,Python Programming, 1/e,36,Functions and Parameters: The Detail

33、s,Python Programming, 1/e,37,Functions and Paramters: The Details,One thing not addressed in this example was multiple parameters. In this case the formal and actual parameters are matched up based on position, e.g. the first actual parameter is assigned to the first formal parameter, the second act

34、ual parameter is assigned to the second formal parameter, etc.,Python Programming, 1/e,38,Functions and Parameters: The Details,As an example, consider the call to drawBar: drawBar(win, 0, principal) When control is passed to drawBar, these parameters are matched up to the formal parameters in the f

35、unction heading: def drawBar(window, year, height):,Python Programming, 1/e,39,Functions and Parameters: The Details,The net effect is as if the function body had been prefaced with three assignment statements: window = win year = 0 height = principal,Python Programming, 1/e,40,Getting Results from

36、a Function,Passing parameters provides a mechanism for initializing the variables in a function. Parameters act as inputs to a function. We can call a function many times and get different results by changing its parameters.,Python Programming, 1/e,41,Functions That Return Values,Weve already seen n

37、umerous examples of functions that return 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 returns the square root of its argument.,Python Programming, 1/e,42,Functions That Return Values,This function returns the square of a n

38、umber: def square(x): return x*x When Python encounters return, it exits the function and returns control to the point where the function was called. In addition, the value(s) provided in the return statement are sent back to the caller as an expression result.,Python Programming, 1/e,43,Functions T

39、hat Return Values, square(3) 9 print square(4) 16 x = 5 y = square(x) print y 25 print square(x) + square(3) 34,Python Programming, 1/e,44,Functions That Return Values,We can use the square function to write a routine to calculate the distance between (x1,y1) and (x2,y2).def distance(p1, p2): dist =

40、 math.sqrt(square(p2.getX() - p1.getX() + square(p2.getY() - p1.getY() return dist,Python Programming, 1/e,45,Functions That Return Values,Sometimes a function needs to return more than one value. To do this, simply list more than one expression in the return statement.def sumDiff(x, y): sum = x + y

41、 diff = x y return sum, diff,Python Programming, 1/e,46,Functions That Return Values,When calling this function, use simultaneous assignment. num1, num2 = input(“Please enter two numbers (num1, num2) “) s, d = sumDiff(num1, num2) print “The sum is“, s, “and the difference is“, dAs before, the values

42、 are assigned based on position, so s gets the first value returned (the sum), and d gets the second (the difference).,Python Programming, 1/e,47,Functions That Return Values,One “gotcha” all Python functions return a value, whether they contain a return statement or not. Functions without a return

43、hand back a special object, denoted None. A common problem is writing a value-returning function and omitting the return!,Python Programming, 1/e,48,Functions That Return Values,If your value-returning functions produce strange messages, check to make sure you remembered to include the return!,Pytho

44、n Programming, 1/e,49,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 master

45、y of some subtle details about how assignment works and the relationship between actual and formal parameters.,Python Programming, 1/e,50,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 a

46、ccount. Lets look at a first-cut at the function. def addInterest(balance, rate): newBalance = balance * (1 + rate) balance = newBalance,Python Programming, 1/e,51,Functions that Modify Parameters,The intent is to set the balance of the account to a new value that includes the interest amount. Lets

47、write a main program to test this: def test(): amount = 1000 rate = 0.05 addInterest(amount, rate) print amount,Python Programming, 1/e,52,Functions that Modify Parameters,We hope that that the 5% will be added to the amount, returning 1050. test() 1000 What went wrong? Nothing!,Python Programming,

48、1/e,53,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 = newBalancedef test():amount

49、= 1000rate = 0.05addInterest(amount, rate)print amount,Python Programming, 1/e,54,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 = newBalancedef test():amount = 1000rate = 0.05addInterest(amount, rate)print amount,

本站链接:文库   一言   我酷   合作


客服QQ:2549714901微博号:道客多多官方知乎号:道客多多

经营许可证编号: 粤ICP备2021046453号世界地图

道客多多©版权所有2020-2025营业执照举报