资源预览内容
第1页 / 共6页
第2页 / 共6页
第3页 / 共6页
第4页 / 共6页
第5页 / 共6页
亲,该文档总共6页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述
FunctionsChapter 4Python for Informatics: Exploring Informationww.pythonlearn.comUnless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution 3.0 License.htp:/creativecommons.org/licenses/by/3.0/.Copyright 2010- Charles R. SeveranceStored (and reused) StepsOutput:HelloFunZipHelloFunProgram:def hello():print Helloprint Funhello()print Ziphello()defprint Helloprint Funhello()print “Zip”We cal these reusable pieces of code “functions”.hello():hello()Python FunctionsThere are two kinds of functions in Python.Built-in functions that are provided as part of Python - raw_input(), type(), float(), int() .Functions that we define ourselves and then useWe treat the of the built-in function names as new reserved words (i.e. we avoid them as variable names)Function DefinitionIn Python a function is some reusable code that takes arguments(s) as input does some computation and then returns a result or resultsWe define a function using the def reserved wordWe cal/invoke the function by using the function name, parenthesis and arguments in an expression big = max(Hello world) print bigw tiny = min(Hello world) print tinybig = max(Hello world)ArgumentwResultAssignmentMax Function big = max(Hello world) print bigwmax()function“Hello world” (a string)w(a string)A function is some stored code that we use. A function takes some input and produces an output.Guido wrote this codeMax Function big = max(Hello world) print bigwdef max(inp):blahblahfor x in y:blahblah“Hello world” (a string)w(a string)A function is some stored code that we use. A function takes some input and produces an output.Guido wrote this codeType ConversionsWhen you put an integer and floating point in an expression the integer is implicitly converted to a floatYou can control this with the built in functions int() and float() print float(99) / 1000.99 i = 42 type(i) f = float(i) print f42.0 type(f) print 1 + 2 * float(3) / 4 - 5-2.5 String ConversionsYou can also use int() and float() to convert between strings and integersYou wil get an error if the string does not contain numeric characters sval = 123 type(sval) print sval + 1Traceback (most recent cal last):File , line 1, in TypeError: cannot concatenate str and int ival = int(sval) type(ival) print ival + 1124 nsv = hello bob niv = int(nsv)Traceback (most recent cal last):File , line 1, in ValueError: invalid literal for int() Building our Own FunctionsWe create a new function using the def keyword folowed by optional parameters in parenthesis.We indent the body of the functionThis defines the function but does not execute the body of the functiondef print_lyrics():print Im a lumberjack, and Im okay.print I sleep al night and I work al day.x = 5print Hellodef print_lyrics():print Im a lumberjack, and Im okay.print I sleep al night and I work al day.print Yox = x + 2print xHelloYo7print Im a lumberjack, and Im okay.print I sleep al night and I work al day.print_lyrics():Definitions and UsesOnce we have defined a function, we can cal (or invoke) it as many times as we likeThis is the store and reuse patternx = 5print Hellodef print_lyrics():print Im a lumberjack, and Im okay.print I sleep al night and I work al day.print Yoprint_lyrics()x = x + 2print xHelloYoIm a lumberjack, and Im okay.I sleep al night and I work al day.7ArgumentsAn argument is a value we pas into the function as its input when we cal the functionWe use arguments so we can direct the function to do different kinds of work when we cal it at different timesWe put the arguments in parenthesis after the name of the functionbig = max(Hello world)ArgumentParametersA parameter is a variable which we use in the function definition that is a “handle” that alows the code in the function to access the arguments for a particular function invocation. def greet(lang):. if lang = es:. print Hola. elif lang = fr:. print Bonjour. else:. print Hello. greet(en)Hello greet(es)Hola greet(fr)Bonjour Return ValuesOften a function wil take its arguments, do some computation and return a value to be used as the value of the function cal in the caling expression. The return keyword is used for this.def greet():return Helloprint greet(), Glennprint greet(), SallyHello GlennHello SallyReturn ValueA “fruitful” function is one that produces a result (or return value)The return statement ends the function execution and “sends back” the result of the function def greet(lang):. if lang = es:. return Hola. elif lang = fr:. return Bonjour. else:. return Hello. print greet(en),GlennHello Glenn print greet(es),SalyHola Saly
收藏 下载该资源
网站客服QQ:2055934822
金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号