python-lectures-5_第1页
python-lectures-5_第2页
python-lectures-5_第3页
python-lectures-5_第4页
python-lectures-5_第5页
已阅读5页,还剩23页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Python Crash CourseFunctions, Modules,Bachelors V1.0 dd 20-01-2014 Hour 1,Introduction to language - functions,What are functions A function is a piece of code in a program. The function performs a specific task. The advantages of using functions are: Reducing duplication of code Decomposing complex

2、 problems into simpler pieces Improving clarity of the code Reuse of code Information hiding Functions in Python are first-class citizens. It means that functions have equal status with other objects in Python. Functions can be assigned to variables, stored in collections or passed as arguments. Thi

3、s brings additional flexibility to the language. Function types There are two basic types of functions. Built-in functions and user defined ones. The built-in functions are part of the Python language. Examples are:dir(),len()orabs().,Introduction to language - functions, def my_func(x, y, z): . a =

4、 x + y . b = a * z . return b . ,Defining Functions Here are simple rules to define a function in Python: Function blocks begin with the keyworddeffollowed by the function name and parentheses ( ). Any input parameters or arguments should be placed within these parentheses. You can also define param

5、eters inside these parentheses. The code block within every function starts with a colon : and is indented. The statement return expression exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None., my_func(1.0, 3.0, 2.0)

6、8.0 my_func(1.0, 3.0, 1.0) 4.0 my_func(5.0, 0.0, 1.0) 5.0 my_func(2.0, 0,0 3.0) 6.0,Introduction to language - functions,#!/usr/bin/python def f1(): print f1() f1() #f2() def f2(): print f2(),Defining Functions Function must be denifed preceding their usage:,#!/usr/bin/python def f(): print f() func

7、tion def g(): def f(): print f() inner function f() f() g(),uncommenting f2() will cause a NameError,where to define functions,inner function definition,Introduction to language - functions,Functions are objects, def f(): . This function prints a message . print Today it is a cloudy day . f._doc_ Th

8、is function prints a message f() Today it is a cloudy day id(f) 140491806602016 , def f(): . pass . def g(): . pass . def h(f): . print id(f) . a=(f, g, h) for i in a: . print i . h(f) 140491806602016 h(g) 140491806602136 ,Introduction to language - functions,Functions types always available for usa

9、ge those contained in external modules programmer defined, from math import sqrt def cube(x): . return x * x * x . print abs(-1) 1 print cube(9) 729 print sqrt(81) 9.0,Introduction to language - functions,The return keyword is used to return value no return returns None, def cube(x): . return x * x

10、* x . def showMessage(msg): . print msg . x = cube(3) print x 27 showMessage(Some text) Some text print showMessage(O, no!) O, no! None showMessage(cube(3) 27 , n = 1, 2, 3, 4, 5 def stats(x): . mx = max(x) . mn = min(x) . ln = len(x) . sm = sum(x) . . return mx, mn, ln, sm . mx, mn, ln, sm = stats(

11、n) print stats(n) (5, 1, 5, 15) print mx, mn, ln, sm 5 1 5 15,Introduction to language - functions, def fact(n): . if(n=0): return 1; . m = 1; . k = 1; . while(n = k): . m = m * k; . k = k + 1; . return m;,Recursion: def fact(n): . if n 0: . return n * fact(n-1) # Recursive call . return 1# exits fu

12、nction returning 1 print fact(100) print fact(1000),Introduction to language - functions, def C2F(c): . return c * 9/5 + 32 . print C2F(100) 212 print C2F(0) 32 print C2F(30) 86 ,Function arguments,single arguments, def power(x, y=2): . r = 1 . for i in range(y): . r = r * x . return r . print power

13、(3) 9 print power(3, 3) 27 print power(5, 5) 3125 ,multiple arguments,Introduction to language - functions, def display(name, age, sex): . print Name: , name . print Age: , age . print Sex: , sex . display(age=43, name=Lary, sex=M) Name: Lary Age: 43 Sex: M display(name=Joan, age=24, sex=F) Name: Jo

14、an Age: 24 Sex: F display(Joan, sex=F, age=24) Name: Joan Age: 24 Sex: F display(age=24, name=Joan, F) File , line 1 SyntaxError: non-keyword arg after keyword arg ,Function arguments,named arguments,order may be changed default value,Introduction to language - functions, def sum(*args): . Function

15、returns the sum . of all values . s = 0 . for i in args: . s += i . return s . print sum._doc_ Function returns the sum of all values print sum(1, 2, 3) 6 print sum(1, 2, 3, 4, 5) 15 ,Function arguments,arbitrary number of arguments,Introduction to language - functions, n = 1, 2, 3, 4, 5 print Origi

16、nal list:, n Original list: 1, 2, 3, 4, 5 def f(x): . x.pop() . x.pop() . x.insert(0, 0) . print Inside f():, x . . f(n) Inside f(): 0, 1, 2, 3 print After function call:, n After function call: 0, 1, 2, 3 ,Function arguments,passing by reference Passing objects by reference has two important conclu

17、sions. The process is faster than if copies of objects were passed. Mutable objects that are modified in functions are permanently changed.,Introduction to language - functions, name = Jack def f(): . name = Robert . print Within function, name . print Outside function, name Outside function Jack f(

18、) Within function Robert def f(): . print Within function, name . print Outside function, name Outside function Jack f() Within function Jack ,Function variables,Global and Local A variable defined in a function body has a local scope We can get the contents of a global variable inside the body of a

19、 function. But if we want to change a global variable in a function, we must use the global keyword., name = Jack def f(): . global name . name = Robert . print Within function, name . print Outside function, name Outside function Jack f() Within function Robert print Outside function, name Outside

20、function Robert ,Introduction to language - functions,TheAnonymousFunctions: You can use thelambdakeyword to create small anonymous functions. These functions are called anonymous because they are not declared by using thedef keyword. Lambda forms can take any number of arguments but return just one

21、 value in the form of an expression. They cannot contain commands or multiple expressions. An anonymous function cannot be a direct call to print because lambda requires an expression. Lambda functions have their own local namespace and cannot access variables other than those in their parameter lis

22、t and those in the global namespace.,#!/usr/bin/python # Function definition is here sum = lambda arg1, arg2: arg1 + arg2; # Now you can call sum as a function print Value of total : , sum( 10, 20 ) print Value of total : , sum( 20, 20 ) Value of total : 30 Value of total : 40,Introduction to langug

23、e - Modules,What are modules for? Python modules are used to organize Python code. For example, database related code is placed inside a database module, security code in a security module etc. Smaller Python scripts can have one module. But larger programs are split into several modules. Modules ar

24、e grouped together to form packages. Modules names A module name is the file name with the .py extension. When we have a file called empty.py, empty is the module name. The _name_ is a variable that holds the name of the module being referenced. The current module, the module being executed (called

25、also the main module) has a special name: _main_. With this name it can be referenced from the Python code.,Introduction to language - Modules,$ cat hello.py def print_func( par ): print Hello : , par return,#!/usr/bin/python # Import module hello import hello # Now you can call defined function tha

26、t module as follows hello.print_func(“Earth),Hello : Earth, print _name_ _main_ print hello._name_ hello ,Importing into the current namespace should be done with care due to name clashes,Introduction to languge - Modules,When you import a module, the Python interpreter searches for the module in th

27、e following sequences: The current directory. If the module isnt found, Python then searches each directory in the shell variable PYTHONPATH. If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/lib64/python2.7/. The module search path is stored in the syste

28、m module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default. PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable PATH. /softw

29、are/local/lib64/python2.7/site-packages /usr/lib64/python2.7/site-packages,Introduction to language - modules,Modules are searched for in the following places: the current working directory (for interactive sessions) the directory of the top-level script le (for script les) the directories dened in

30、PYTHONPATH Standard library directories, # Get the complete module search path: import sys print sys.path , /software/local/lib64/python2.7/site-packages/Astropysics-0.1.dev_r1161-py2.7.egg, /software/local/lib64/python2.7/site-packages/CosmoloPy-0.1.104-py2.7-linux-x86_64.egg, /software/local/lib64

31、/python2.7/site-packages/pyregion-1.1_git-py2.7-linux-x86_64.egg, /software/local/lib64/python2.7/site-packages/scikit_image-0.9dev-py2.7-linux-x86_64.egg, /software/local/lib64/python2.7/site-packages/memory_profiler-0.26-py2.7.egg, /software/local/lib64/python2.7/site-packages/agpy-0.1.1-py2.7.egg

32、, /software/local/lib64/python2.7/site-packages/APLpy-0.9.12-py2.7.egg, /software/local/lib64/python2.7/site-packages/pandas-0.14.1-py2.7-linux-x86_64.egg, /software/local/lib64/python2.7/site-packages/astroquery-0.2.3-py2.7.egg, /software/local/lib64/python2.7/site-packages/html5lib-1.0b3-py2.7.egg

33、, /software/local/lib64/python2.7/site-packages/beautifulsoup4-4.3.2-py2.7.egg, /software/local/lib64/python2.7/site-packages/requests-2.4.3-py2.7.egg, /software/local/lib64/python2.7/site-packages/PIL-1.1.7-py2.7-linux-x86_64.egg, /software/local/lib64/python2.7/site-packages/astLib-0.8.0-py2.7-lin

34、ux-x86_64.egg, /software/local/lib64/python2.7/site-packages/setuptools-6.0.2-py2.7.egg, /software/local/lib64/python2.7/site-packages/pip-1.5.6-py2.7.egg, /software/local/lib64/python2.7/site-packages/Jinja-1.2-py2.7-linux-x86_64.egg, /software/local/lib64/python2.7/site-packages/Jinja2-2.7.3-py2.7

35、.egg, /software/local/lib64/python2.7/site-packages/pyraf-2.1.6-py2.7-linux-x86_64.egg, /software/local/lib64/python2.7/site-packages/pyfits-3.1.6-py2.7-linux-x86_64.egg, /software/local/lib64/python2.7/site-packages/numexpr-2.4-py2.7-linux-x86_64.egg, /software/local/lib64/python2.7/site-packages/t

36、ables-3.1.1-py2.7-linux-x86_64.egg, /usr/lib/python2.7/site-packages/lmfit-0.7.4-py2.7.egg, /usr/lib64/python2.7/site-packages/mpich, /software/fc20/lib64/python2.7/site-packages, /software/local/lib64/python2.7/site-packages, /home/deul/.local/lib/python2.7/site-packages, /usr/lib64/python27.zip, /

37、usr/lib64/python2.7, /usr/lib64/python2.7/plat-linux2, /usr/lib64/python2.7/lib-tk, /usr/lib64/python2.7/lib-old, /usr/lib64/python2.7/lib-dynload, /usr/lib64/python2.7/site-packages, /usr/lib64/python2.7/site-packages/Numeric, /usr/lib64/python2.7/site-packages/gst-0.10, /usr/lib64/python2.7/site-p

38、ackages/gtk-2.0, /usr/lib64/python2.7/site-packages/wx-2.8-gtk2-unicode, /usr/lib/python2.7/site-packages,Introduction to language - modules,Frequently used modules sys Information about Python itself (path, etc.) os Operating system functions os.path Portable pathname tools shutil Utilities for cop

39、ying les and directory trees cmp Utilities for comparing les and directories glob Finds les matching wildcard pattern re Regular expression string matching time Time and date handling datetime Fast implementation of date and time handling doctest, unittest Modules that facilitate unit test,Introduct

40、ion to language - modules,More frequently used modules pdb Debugger hotshot Code proling pickle, cpickle, marshal, shelve Used to save objects and code to les getopt, optparse Utilities to handle shell-level argument parsing math, cmath Math functions (real and complex) faster for scalars random Ran

41、dom generators (likewise) gzip read and write gzipped les struct Functions to pack and unpack binary data structures StringIO, cStringIO String-like objects that can be read and written as les (e.g., in-memory les) types Names for all the standard Python type,Introduction to language - modules,Modul

42、es can contain any code Classes, functions, denitions, immediately executed code Can be imported in own namespace, or into the global namespace, import math math.cos(math.pi) -1.0 math.cos(pi) Traceback (most recent call last): File , line 1, in NameError: name pi is not defined from math import cos

43、, pi cos(pi) -1.0 from math import *,Introduction to language - modules,Module import This construct will import all Python definitions into the namespace of another module. he use of this import construct may result in namespace pollution. We may have several objects of the same name and their defi

44、nitions can be overridden. No _ names are imported, from math import *,#!/usr/bin/python names is a test module _version = 1.0 names = Paul, Frank, Jessica def show_names(): for i in names: print i def _show_version(): print _version, from names import * print locals() _builtins_: , _file_: ./privat

45、e.py, show_names: , names: Paul, Frank, Jessica, _name_: _main_, _doc_: None show_names() Paul Frank Jessica,Introduction to language - modules,Use from.import and import.as with care. Both make your code harder to understand. Do not sacrice code clearness for some keystrokes! In some cases, the use

46、 is acceptable: In interactive work (import math as m) If things are absolutely clear (e.g. all functions of an imported module obey a clear naming convention; cts_xyz) import. as: As last resort in case of name clashes between module names, from math import sin print sin(1.0) print cos(1.0) # wont

47、work from math import * # All attributes copied to global namespace Extremely dangerous print tan(1.0),Introduction to language - modules, import numpy dir(numpy) ALLOW_THREADS, BUFSIZE, CLIP, ComplexWarning, DataSource, ERR_CALL, ERR_DEFAULT, ERR_DEFAULT2, ERR_IGNORE, ERR_LOG, ERR_PRINT, ERR_RAISE,

48、 ERR_WARN, FLOATING_POINT_SUPPORT, FPE_DIVIDEBYZERO, FPE_INVALID, FPE_OVERFLOW, FPE_UNDERFLOW, False_, Inf, Infinity, MAXDIMS, MachAr, NAN, NINF, NZERO, NaN, PINF, PZERO, PackageLoader, RAISE, RankWarning, SHIFT_DIVIDEBYZERO, SHIFT_INVALID, SHIFT_OVERFLOW, SHIFT_UNDERFLOW, ScalarType, Tester, True_,

49、 UFUNC_BUFSIZE_DEFAULT, UFUNC_PYVALS_NAME, WRAP, _NUMPY_SETUP_, _all_, _builtins_, _config_, _doc_, _file_, _git_revision_, _name_, _package_, _path_, _version_, _import_tools, _mat, abs, absolute, add, add_docstring, add_newdoc, add_newdocs, alen, all, allclose, alltrue, alterdot, amax, amin, angle, any, append, apply_along_axis, . typeNA, typecodes, typename, ubyte, ufunc, uint, uint0, uint16, uint32, uint64, uint8, uintc, uintp, ulonglong, unicode, unicode0, unicode_, union1d, unique, unpackbits, unravel_index, unsignedinteger, unw

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论