Home  >  Article  >  Backend Development  >  Introduction to python basic teaching

Introduction to python basic teaching

巴扎黑
巴扎黑Original
2017-06-23 16:32:542099browse

Section 9 Function

  • A function is a group of statements that completes a specific function. This group of statements can be used as a unit and given a name.

  • You can use the function name to execute it multiple times in different places in the program (this is usually called a function call), but there is no need to write these statements repeatedly in all places.

Custom function

  • User-written

Predefined Python function

  • Some functions that come with the system, and some functions written by third parties, such as some functions written by other programmers, users can use these ready-made functions directly.

Why use functions

  • Reduce the difficulty of programming

    • Usually a complex Decompose a large problem into a series of simpler small problems, and then continue to divide the small problems into smaller problems. When the problem is refined enough to be simple, we will be able to divide and conquer. At this time, we can use functions to deal with specific problems. Once each small problem is solved, the big problem will be solved.

  • Code Reuse

    • The functions we define can be used in multiple places in a program, and can also be used Multiple programs. In addition, we can also put functions into a module for use by other programmers, and we can also use functions defined by other programs. This avoids duplication of work and improves work efficiency.

Function definition and calling

  • When we define a function ourselves, we usually use the def statement, whose syntax is as follows :

    def 函数名 (参数列表): #可以没有参数函数体
    
    def add(a, b):
        print a + b
  • The general form of calling a function is:

    函数名(参数列表)
    
    add(1, 2)

Formal parameters and actual parameters

  • When defining a function, the variable name in parentheses after the function is called "formal parameter", or simply "formal parameter"

  • When calling a function, the variable name in parentheses after the function name The variable name is called "actual parameter", or simply "actual parameter"

Default parameter (default parameter)

  • Default parameter can only Given from right to left, if the first parameter needs to be given a default value and other parameters are not given, then move the first parameter to the last one.

    def add(a, b = 2):
        print a + b
    
    add(3)                  #result : 5

Local and global variables

  • Any variable in Python has its specific scope.

  • Variables defined in a function can generally only be used within the function. These variables that can only be used in specific parts of the program are called local variables.

  • Variables defined at the top of a file can be called by any function in the file. These variables that can be used by the entire program are called global variables.

    x = 100         #全局变量,可以在文件任何地方调用
    
    def func():
        x = 200     #局部变量,只能在函数内部调用
        print x
    
    func()          #输出200
    print x         #输出100

global statement

  • Forced declaration as a global variable

    x = 100
    
    def func():
        global x    #强制声明x为全局变量,导致值被覆盖
        x = 200
    
    func()
    print x         #输出200

Function return value

  • The function will return a specified value after being called

  • The function will return None by default after being called

  • return return value

  • The return value can be of any type

  • returnAfter execution, the function terminates

  • Distinguish between return values ​​and printing

    def add(a, b):
        return a + b
    
    ret = add(1, 2)     #将函数返回结果赋值给变量ret
    print ret           #输出3

Pass tuples and dictionaries to the function

  • func (*args)

    def func(x, y):
        print x, y
    
    t = (1, 2)
    func(*t)
  • func (**kw)

    def func(name='jack', age=30):
        print name,age
    
    d = {'age': 22, 'name' : 'mike'};
    func(**d)

Handling redundant arguments

  • def func(*args, **kw)

    def func(x, *args, **kw):
        print x
        print args
        print kw
    
    func(1, 2, 3, 4, 5, y=10, z=20)
    
    #输出
    1
    (2, 3, 4, 5)
    {'y': 10, 'z': 20}

lambda expression

  • Anonymous function

    • #The lambda function is a minimal function that quickly defines a single line. It is borrowed from Lisp and can be used wherever a function is needed.

      lambda x,y:x*y
    • When using Python to write some execution scripts, using lambda can save the process of defining functions and make the code more streamlined.

    • For some abstract functions that will not be reused elsewhere, it is sometimes difficult to name the function. Using lambda does not require naming issues.

    • Using lambda sometimes makes the code easier to understand.

lambda basics

  • In the lambda statement, there are parameters before the colon. There can be multiple, separated by commas, on the right side of the colon. The return value. What the lambda statement constructs is actually a function object

    g = lambda x:x**2
    print g
    <function <lambda> at 0x0000000002643A58>

lambda application example

  • reduce is to successively operate each item in the list and receive the parameters There are 2, and the final result returned is one result.

    sum = reduce(lambda x,y:x*y, range(1,6))
    print sum

switch statement

  • The switch statement is used to write programs with multi-branch structures, similar to if...elif...else statements .

  • switch语句表达的分支结构比if...elif...else语句表达的更清晰,代码的可读性更高。

  • 但是python并没有提供switch语句

switch实现

  • python可以通过字典实现switch语句的功能。

  • 实现方法分为两步

    • 首先,定义一个字典

    • 其次,调用字典的get()获取相应的表达式

函数调用

  • 通过字典调用函数

    def add(a, b):
        return a + b
    
    def sub(a, b):
        return a - b
    
    def mul(a, b):
        return a * b
    
    def div(a, b):
        return a / b
    
    operator = {'+': add, '-': sub, '*': mul, '/': div}     #通过字典实现switch语句的功能
    
    def calc(a, o, b):
        return operator.get(o)(a, b)
    
    print calc(4, '+', 2)
    print calc(4, '-', 2)
    print calc(4, '*', 2)
    print calc(4, '/', 2)

第十节 内置函数

help函数可以用来查看函数的用法

help(range)

#输出结果
Help on built-in function range in module __builtin__:

range(...)
    range(stop) -> list of integers
    range(start, stop[, step]) -> list of integers

    Return a list containing an arithmetic progression of integers.
    range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
    When step is given, it specifies the increment (or decrement).
    For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
    These are exactly the valid indices for a list of 4 elements.

常用函数

  • abs(number): 绝对值

  • max(iterable[, key=func]): 最大值

  • min(iterable[, key=func]): 最小值

  • len(collection): 取得一个序列或集合的长度

  • divmod(x, y): 求两个数的商和模,返回一个元组(x//y, x%y)

  • pow(x, y[, z]): 求一个数的幂运算

  • round(number[, ndigits]): 对一个数进行指定精度的四舍五入

  • callable(object): 判断一个对象是否可调用

  • isinstance(object, class-or-type-or-tuple):判断对象是否为某个类的实例

  • cmp(x, y): 比较两个数或字符串大小

  • range(start [,stop, step]): 返回一个范围数组,如range(3), 返回[0,1,2]

  • xrange(start [,stop, step]): 作用与range相同,但是返回一个xrange生成器,当生成范围较大的数组时,用它性能较高

类型转换函数

  • type()

    type(object) -> the object's type
    type(name, bases, dict) -> a new type
  • int()

    int(x=0) -> int or long
    int(x, base=10) -> int or long
  • long()

    long(x=0) -> long
    long(x, base=10) -> long
  • float()

    float(x) -> floating point number
  • complex()

    complex(real[, imag]) -> complex number
  • str()

    str(object='') -> string
  • list()

    list() -> new empty list
    list(iterable) -> new list initialized from iterable's items
  • tuple()

    tuple() -> empty tuple
    tuple(iterable) -> tuple initialized from iterable's items
  • hex()

    hex(number) -> string
  • oct()

    oct(number) -> string
  • chr()

    chr(i) -> character
  • ord()

    ord(c) -> integer

string函数

  • str.capitalize()

    >>> s = "hello"
    >>> s.capitalize()
    'Hello'
  • str.replace()

    >>> s = "hello"
    >>> s.replace('h', 'H')
    'Hello'
  • str.split()

    >>> ip = "192.168.1.123"
    >>> ip.split('.')
    ['192', '168', '1', '123']

序列处理函数

  • len()

    >>>l = range(10)
    >>> len(l)
    10
  • max()

    >>>l = range(10)
    >>> max(l)
    9
  • min()

    >>>l = range(10)
    >>> min(l)
    0
  • filter()

    >>>l = range(10)
    >>> filter(lambda x: x>5, l)
    [6, 7, 8, 9]
  • zip()

    >>> name=['bob','jack','mike']
    >>> age=[20,21,22]
    >>> tel=[131,132]
    >>> zip(name, age)
    [('bob', 20), ('jack', 21), ('mike', 22)]
    >>> zip(name,age,tel)
    [('bob', 20, 131), ('jack', 21, 132)]       #如果个数不匹配会被忽略
  • map()

    >>> map(None, name, age)
    [('bob', 20), ('jack', 21), ('mike', 22)]
    >>> map(None, name, age, tel)
    [('bob', 20, 131), ('jack', 21, 132), ('mike', 22, None)]       #个数不匹配时,没有值的会被None代替
    
    >>> a = [1,3,5]
    >>> b = [2,4,6]
    >>> map(lambda x,y:x*y, a, b)
    [2, 12, 30]
  • reduce()

    >>> reduce(lambda x,y:x+y, range(1,101))
    5050

lambda -> 列表表达式

  • map的例子,可以写成

    print map(lambda x:x*2+10, range(1,11))
    print [x*2+10 for x in range(1,11)]
  • 非常的简洁,易懂。filter的例子可以写成:

    print filter(lambda x:x%3==0, range(1,11))
    print [x for x in range(1,11) if x%3 == 0]


第十一节 模块

简介

  • 模块是python组织代码的基本方式

  • python的脚本都是用扩展名为py的文本文件保存的,一个脚本可以单独运行,也可以导入另一个脚本中运行。当脚本被导入运行时,我们将其称为模块(module)

  • python的模块可以按目录组织为包

  • 创建一个包的步骤是:

    • 建立一个名字为包名字的文件夹

    • 在该文件夹下创建一个__init__.py文件

    • 根据需要在该文件夹下存放脚本文件、已编译扩展及子包

    • import pack.m1, pack.m2, pack.m3

模块

  • 模块名与脚本的文件名相同

    • 例如我们编写了一个名为items.py的脚本,则可在另外一个脚本中用import items语句来导入它

总结

  • 模块是一个可以导入的python脚本文件

  • 包是一堆目录组织的模块和子包,目录下的__init__.py文件存放了包的信息

  • 可以用import, import as, from import等语句导入模块和包

    #假设有一个模块名为calc.py
    import calc
    import calc as calculate
    from calc import add


第十二节 正则表达式

目标

  • 掌握正则表达式的规则

案例

  • 一个小爬虫

简介

  • 正则表达式(或re)是一种小型的、高度专业化的编程语言,(在python中)它内嵌在python中,并通过re模块实现

    • 可以为想要匹配的相应字符串集指定规则

    • 该字符集可能包含英文语句、e-mail地址、命令或任何你想搞定的东西

    • 可以问诸如“这个字符串匹配该模式吗”

    • “在这个字符串中是否有部分匹配该模式呢?”

    • 你也可以使用re以各种试来修改或分割字符串

  • 正则表达式模式被编译成一系列的字节码,然后由C编写的匹配引擎执行

  • 正则表达式语言相对小型和受限(功能有限)

    • 并非所有字符串处理都能用正则表达式完成

字符匹配

  • 普通字符

    • 大多数字母和数字一般都会和自身匹配

    • 如正则表达式test会和字符串"test"完全匹配

  • 元字符

    .   ^   $   *   +   ?   {}  []  \   |   ()
    • 其中mn是十进制整数。该限定符的意思是至少有m个重复,至多到n个重复

    • 忽略m会认为下边界是0,而忽略n的结果将是上边界为无穷大(实现上是20亿)

    • {0,}等同于*{1,}等同于+,而{0,1}则与?相同。如果可以的话,最好使用*+?

    • 匹配一次或零次,你可以认为它用于标识某事物是可选的

    • 表示匹配一次或更多次

    • 注意和+之间的不同:匹配零或更多次,所以可以根本不出现,而+则要求至少出现一次

    • 指定前一个字符可能被匹配零次或更多次,而不是只有一次。匹配引擎会试着重复尽可能多的次数(不超过整数界定范围,20亿)

    • 正则表达式第一功能是能够匹配不定长的字符集,另一个功能就是可以指定正则表达式的一部分的重复次数。

    • 反斜杠后面可以加不同的字符以表示不同特殊意义

    • 也可以用于取消所有的元字符:\[\\

      \d  匹配任何十进制数,它相当于[0-9]
      \D  匹配任何非数字字符,它相当于[^0-9]
      \s  匹配任何空白字符,它相当于[\t\n\r\f\v]
      \S  匹配任何非空白字符,它相当于[^\t\n\r\f\v]
      \w  匹配任何字母数字字符,它相当于[a-zA-Z0-9]
      \W  匹配任何非字母数字字符,它相当于[^a-zA-Z0-9]
    • 匹配行尾,行尾被定义为要么是字符串尾,要么是一个换行字符后面的任何位置。

    • 匹配行首。除非设置MULTILINE标志,它只是匹配字符串的开始。在MULTILINE模式里,它也可以匹配字符串中的每个换行。

    • 常用来指定一个字符集:[abc]  [a-z]

    • 元字符在字符集中不起作用:[akm$]

    • 补集匹配不在区间范围内的字符:[^5]

      import re
      
      regExp = r't[0-9]p'
      print re.findall(regExp, 't1p t2p')
    • []

    • ^

    • $

    • \

    • 重复

    • *

    • +

    • ?

    • {m,n}

    使用正则表达式

    • re模块提供了一个正则表达式引擎的接口,可以让你将REstring编译成对象并用它们来进行匹配

    • 编译正则表达式

      >>> import re
      >>> p = re.compile('ab*')
      >>> print p
      <_sre.SRE_Pattern object at 0x00000000004D1CA8>
    • re.compile()也可以接受可选择的标志参数,常用来实现不同的特殊功能和语法变更

      p = re.compile('ab*', re.IGNORECASE)

    反斜杠的麻烦

    • 字符串前加"r"反斜杠就不会被任何特殊方式处理

      字符            阶段
      \section        要匹配的字符串
      \\section       为re.compile取消反斜杠的特殊意义
      "\\\\section"   为"\\section"的字符串实值(string literals)取消反斜杠的特殊意义

    执行匹配

    • 'RegexObject'实例有一些方法和属性,完整的列表可查阅Python Library Reference

      方法/属性       作用
      match()        决定RE是否在字符串刚开始的位置匹配
      search()       扫描字符串,找到这个RE匹配的位置
      findall()      找到RE匹配的所有子串,并把它们作为一个列表返回
      finditer()     找到RE匹配的所有子串,并把它们作为一个迭代器返回
      
      如果没有匹配到的话,match()和search()将返回None。
      如果成功的话,就会返回一个'MatchObject'实例。
    • MatchObject实例方法

      方法/属性       作用
      group()        返回被RE匹配的字符串
      start()        返回匹配开始的位置
      end()          返回匹配结束的位置
      span()         返回一个元组包含匹配(开始,结束)的位置
      • 实际程序中,最常见的作法是将'MatchObject'保存在一个变量里,然后检查它是否为None

        p = re.compile('ab*', re.I)
        m = p.match('aaaabcccccabcc')
        
        if m:
            print 'Match found : ', m.group()
        else:
            print 'No match'

    模块级函数

    • re模块也提供了顶级函数调用如match()、search()、sub()、subn()、split()、findall()

    • 查看模块的所有属性和方法: dir(re)

    编译标志-flags

    标志                含义
    DOTALL, S           使.匹配包括换行在内的所有字符
    IGNORECASE, I       使匹配对大小写不敏感
    LOCALE, L           做本地化识别(local-aware)匹配.法语等
    MULTILINE, M        多行匹配,影响^和$
    VERBOSE, X          能够使用REs的verbose状态,使之被组织得更清晰易懂
    
    charref = re.compile(r"""
    (
    [0-9]+[^0-9]    #Decimal form
    | 0[0-7]+[^0-7] #Octal form
    | x[0-9a-fA-F]+[^0-9a-fA-F] #Hexadecimal form
    )
    """, re.VERBOSE)

    分组()

    email = r"\w+@\w+(\.com|\.cn)"

    一个小爬虫

    • 下载贴吧或空间中所有图片

      import re
      import urllib
      
      def getHtml(url):
          page = urllib.urlopen(url)
          html = page.read()
          return html
      
      def getImg(html):
          reg = r'src="(.*?\.jpg)" width'
          imgre = re.compile(reg)
          imglist = re.findall(imgre, html)
          x = 0
          for imgurl in imglist:
              urllib.urlretrieve(imgurl, '%s.jpg' % x)
              x++
      
      getImg(getHtml(url))


    第十三章 python对内存的使用

    浅拷贝和深拷贝

    • 所谓浅拷贝就是对引用的拷贝(只拷贝父对象)

    • 所谓深拷贝就是对对象的资源的拷贝

    • 解释一个例子:

      import copy
      a = [1,2,3,['a','b','c']]
      b = a
      c = copy.copy(a)
      d = copy.deepcopy(a)


    第十四章 文件与目录

    目标

    • 文件的打开和创建

    • 文件读取

    • 文件写入

    • 内容查找和替换

    • 文件删除、复制、重命名

    • 目录操作

    案例

    • 目录分析器

    • 杀毒软件

    • 系统垃圾清理工具

    python文件读写

    • python进行文件读写的函数是openfile

    • file_handle = open(filename, mode)

    模式 说明
    r 只读
    r+ 读写
    w 写入,先删除原文件,在重新写入,如果文件没有则创建
    w+ 读写,先删除原文件,在重新写入,如果文件没有则创建(可以写入输出)
    a 写入,在文件末尾追加新的内容,文件不存在,创建之
    a+ 读写,在文件末尾追加新的内容,文件不存在,创建之
    b 打开二进制文件。可以与r、w、a、+结合使用
    U 支持所有的换行符号。"\r"、"\n"、"\r\n"

    文件对象方法

    • close

      • 关闭文件,关闭前,会将缓存中的数据先写入文件。

      • FileObject.close()

      • 格式

      • 说明

      • readline

        • 每次读取文件的一行

        • size:是指每行每次读取size个字节,直到行的末尾

        • String = FileObject.readline([size])

        • 格式

        • 说明

        • readlines

          • 多行读,返回一个列表

          • size: 每次读入size个字符,然后继续按size读,而不是每次读入行的size个字符

          • List = FileObject.readlines([size])

          • 格式

          • 说明

          • read

            • 读出文件的所有内容,并复制给一个字符串

            • size: 读出文件的前[size]个字符,并输出给字符串,此时文件的指针指向size处

            • String = FileObject.read([size])

            • 格式

            • 说明

            • next

              • 返回当前行,并将文件指针到下一行

              • FileObject.next()

              • 格式

              • 说明

              • write

                • write和后面的writelines在写入前会是否清除文件中原来所有的数据,在重新写入新的内容,取决于打开文件的模式

                • FileObject.write(string)

                • 格式

                • 说明

                • writelines

                  • 多行写

                  • 效率比write高,速度更快,少量写入可以使用write

                  • FileObject.writelines(List)

                  • 格式

                  • 说明

                  • seek

                    • 选项=0时,表示将文件指针指向从文件头部到“偏移量”字节处。

                    • 选项=1时,表示将文件指针指向从文件的当前位置,向向移动“偏移量”字节。

                    • 选项=2时,表示将文件指针指向从文件的尾部,向前移动“偏移量”字节。

                    • FileObject.seek(偏移量,选项)

                    • 格式

                    • 说明

                    • flush

                      • 提交更新

                      • FileObject.flush()

                      • 格式

                      • 说明

                      文件查找和替换

                      • 文件查找

                      • cat a.txt

                        hello world
                        hello hello world
                      • 统计文件中hello的个数

                        import re
                        
                        fp = file("a.txt", "r")
                        count = 0
                        for s in fp.readlines():
                            li = re.findall("hello", s)
                            if len(li) > 0:
                                count = count + len(li)
                        
                        print "Search ",count," hello"
                        fp.close()
                      • 文件内容替换

                      • 问题:把a.txt中的hello替换为good, 并保存结果到b.txt中

                      • 示例代码一:

                        fp1 = file("a.txt", "r")
                        fp2 = file("b.txt", "w")
                        
                        for s in fp1.readlines():
                            fp2.write(s.replace("hello", "good"))
                        
                        fp1.close()
                        fp2.close()
                      • 示例代码二:

                        fp1 = file("a.txt", "r")
                        fp2 = file("b.txt", "w")
                        
                        s = fp1.read()
                        fp2.write(s.replace("hello", "good"))
                        
                        fp1.close()
                        fp2.close()

                      目录操作

                      • 目录操作就是通过python来实现目录的创建,修改,遍历等功能

                      • import os

                        • 目录操作需要调用os模块

                        • 比如os.mkdir('/root/demo')

                      • 常用函数

                      函数 说明
                      mkdir(path[,mode=0777]) 创建单个目录
                      makedirs(name,mode=511) 创建多层级目录
                      rmdir(path) 删除单个目录
                      removedirs(path) 删除多层级目录
                      listdir(path) 列出目录
                      getcwd() 取得当前目录
                      chdir(path) 切换目录
                      walk(top, topdown=True, onerror=None)
                      • 案例

                        • 系统垃圾清除小工具

                      • 方式

                        • 函数声明:os.walk(path)

                        • 该函数返回一个元组,该元组有3个元素,这3个元素分别表示每次遍历的路径名,目录列表和文件列表。

                          for path, dirlist, filelist in os.walk('.'):
                              for filename in filelist:
                                  print os.path.join(path, filename)
                        • 递归函数

                        • os.walk()函数

                      第十五章 异常处理

                      异常以及异常抛出

                      • 异常抛出机制,为程序开发人员提供了一种在运行时发现错误,进行恢复处理,然后继续执行的能力。下面是一个异常处理实例:

                        try:
                            f = open('unfile.py', 'r')
                        except IOError, e:
                            print False,str(e)
                        
                        False [Errno 2] No such file or directory: 'unfile.py'

                      抛出机制

                      • 如果在运行时发生异常的话,解释器会查找相应的处理语句(称为handler)。

                      • 要是在当前函数里没有找到的话,它会将异常传递给上层的调用函数,看看那里能不能处理。

                      • 如果在最外层(全局“main”)还是没有找到的话,解释器就会退出,同时打印出traceback以便让用户找出错误产生的原因。

                      • 注意:虽然大多数错误会导致异常,但一个异常不一定代表错误。有时候它们只是一个警告,有时候它们可能是一个终止信号,比如退出循环等。

                      finally子句

                      • python提供try-finally子句来表述这样的情况:我们不关心捕捉到是什么错误,无论错误是不是发生,这些代码“必须”运行,比如文件关闭,释放锁,把数据库连接还给连接池等。比如:

                        try:
                            f = open('unfile.py', 'r')
                        except Exception, e:
                            print False,str(e)
                        finally:
                            print "exec finally"

                      raise抛出异常

                      • 到目前为止,我们只讨论了如何捕捉异常,那么如何抛出异常?

                      • 使用raise来抛出一个异常:

                        if 'a' > 5:
                            raise TypeError("Error: 'a' must be integer.")

                      常见的python异常

                      异常 描述
                      AssertionError assert语句失败
                      AttributeError 试图访问一个对象没有的属性
                      IOError 输入输出异常,基本是无法打开文件
                      ImportError 无法引入模块或者包,基本是路径问题
                      IndentationError 语法错误,代码没有正确的对齐
                      IndexError 下标索引超出序列边界
                      KeyError 试图访问你字典里不存在的键
                      KeyBoardInterrupt Ctrl+C被按下
                      NameError 使用一个还未赋予对象的变量
                      SyntaxError python代码逻辑语法出错,不能执行
                      TypeError 传入的对象类型与要求不符
                      UnboundLocalError 试图访问一个还未设置的全局变量,基本上是由于另有一个同名的全局变量,导致你以为在访问
                      ValueError 传入一个不被期望的值,即使类型正确

                      The above is the detailed content of Introduction to python basic teaching. For more information, please follow other related articles on the PHP Chinese website!

                      Statement:
                      The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn