《Py4Inf-04-Functions-PrintPy4Inf-04-Functions-Print》由会员分享,可在线阅读,更多相关《Py4Inf-04-Functions-PrintPy4Inf-04-Functions-Print(6页珍藏版)》请在金锄头文库上搜索。
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.htp:/creativecommons.org/licenses/by/3.0/.Copyright 2010- Charles R. SeveranceStored (and reused) StepsOutput:HelloFunZipHello
2、FunProgram: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(),
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 then
4、 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 Functio
5、n 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 fun
7、ctions 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 sva
8、l = 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
9、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 wo
10、rk 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
11、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 da
12、y.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)Argum
13、entParametersA 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(e
14、n)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(), Sal
15、lyHello 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