《Py4Inf-04-FunctionsPy4Inf-04-Functions》由会员分享,可在线阅读,更多相关《Py4Inf-04-FunctionsPy4Inf-04-Functions(24页珍藏版)》请在金锄头文库上搜索。
1、FunctionsChapter 4Python for Informatics: Exploring IUnless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution 3.0 License.http:/creativecommons.org/licenses/by/3.0/.Copyright 2010- Charles R. SeveranceStored (and reused) StepsOutput:HelloFunZipHell
2、oFunProgram:def hello():print Helloprint Funhello()print Ziphello()defprint Helloprint Funhello()print “Zip”We call 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()
3、, 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 th
4、en returns a result or resultsWe define a function using the def reserved wordWe call/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 Func
5、tion 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
6、” (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
7、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 will get an error if the string does not contain numeric characters
8、 sval = 123 type(sval) print sval + 1Traceback (most recent call 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 call last):File , line 1, in ValueError: invalid literal for int() Bui
9、lding our Own FunctionsWe create a new function using the def keyword followed 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 all night
10、and I work all day.x = 5print Hellodef print_lyrics():print Im a lumberjack, and Im okay.print I sleep all night and I work all day.print Yox = x + 2print xHelloYo7print Im a lumberjack, and Im okay.print I sleep all night and I work all day.print_lyrics():Definitions and UsesOnce we have defined a
11、function, we can call (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 all night and I work all day.print Yoprint_lyrics()x = x + 2print xHelloYoIm a lumberjack, and Im okay.I sleep all night
12、 and I work all day.7ArgumentsAn argument is a value we pass into the function as its input when we call the functionWe use arguments so we can direct the function to do different kinds of work when we call it at different timesWe put the arguments in parenthesis after the name of the functionbig =
13、max(Hello world)ArgumentParametersA parameter is a variable which we use in the function definition that is a “handle” that allows 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:
14、. print Hello. greet(en)Hello greet(es)Hola greet(fr)Bonjour Return ValuesOften a function will take its arguments, do some computation and return a value to be used as the value of the function call in the calling expression. The return keyword is used for this.def greet():return Helloprint greet()
15、, 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:. r