Python基础篇:从0开始学python

目录

  1. 数据类型

    • 基本数据类型
    • 整形Int的内置方法
    • 字符串Str的内置方法
    • 列表(待补充)
  2. 流程控制
    • 分支结构if...else...
    • for循环
    • 循环控制
    • while循环
  3. 函数
    • 函数的名称与格式
    • 参数
    • 返回值
    • 作用域
    • 递归和lambda
    • 内置函数
  4. 正则表达式
    • 元字符
    • 内置属性

  1. 数据类型

    • 基本数据类

      • 数字【整型int/long,浮点型float/complex】
        • Python3已经把int和long整合了, 相互转化会自动进行
        • int在32bit机器32位宽,64bit机器64bit宽。
        • i=1 ; j=int(10)
      • 字符串string
        • myname="ben" ; yourname=str("Jin")
      • 布尔boolean
        • True或者False  分别对应1和0  注意大小写
        • bool(0);bool(42);bool('this is a test')
      • 列表list
        1. L=[123,’abc’,1.23]; L=list(123,’abc’,1.23)
      • 元组tuple
        • T=(1,2,3); T=tuple(L)
      • 字典dict
        • D={‘food’:’Spam’, ‘quantity’:4, ‘color’:’pink’}; D=dict(name=’Bob’,age=’42’)
      • 集合set
        • S=set([1,2,3])
      • 日期date
        • import datetime; d=datetime.datetime(2016,11,05)
    • 整形Int的内置方法

      • Int是整形数据类型的一种。int类型的变量可以通过i=5或者i=int(5)两种方式。

        i=5
        print("i的值是%d,类型是%s" %(i,type(i)))
        
        
        j=int(10)
        print("j的值是%d,类型是%s" %(j,type(j)))
        
        =================================
        返回结果:
        i的值是5,类型是<class 'int'>
        j的值是10,类型是<class 'int'>
      • int类型的对象也有着自己的方法,(方法存在int类中存储)

        1. bit_length  二进制的最小位数的长度

        i=5 ##二进制是101
        print(bin(i))
        print(i.bit_length())
        
        =======================
        返回结果:
        0b101
        3

        2.__abs__ 绝对值 等同内置方法 abs()

        i=-5
        print(i.__abs__())
        print(abs(i))
        ================
        返回结果
        5
        5

        3. __add__ 加法  等同于+

        i=-5
        print(i.__add__(6))
        print(i+6)
        =======================
        返回结果
        1
        1

        4. __and__ 等同于&

        i=2
        j=1
        print(i.__and__(j))
        print(i&j)
        ====================
        返回结果
        0
        0

        5. __bool__ 转换成布尔值 0是False 其他的都为True

        i=-2
        j=-1
        k=0
        l=1
        m=2
        n=1.2
        print(i.__bool__())
        print(j.__bool__())
        print(k.__bool__())
        print(l.__bool__())
        print(m.__bool__())
        print(n.__bool__())
        =======================
        返回结果
        True
        True
        False
        True
        True
        True

        6.__divmod__ 商和余数 等同于/和%

        k=95
        l=10
        print(k.__divmod__(l))
        ===================
        返回结果:(9,5)

        7.__eq__(=), __ge__(>=),__gt__(>),__le__(<=),__lt__(<)

        8.__floot__   转成floot类型

        9.__floordiv__ 地板除 等同于//  是除法取整数

        k=95
        l=10
        print(k/l)
        print(k.__floordiv__(l))
        ========================
        返回结果:
        9.5
        9

        10.__int__ 构造方法 就是在类初始化时候用:

        class Person(object):
          def __init__(self):
              self.name = 'Jim'
              self.age = 23
        if __name__ == '__main__':
           person = Person()
           print person.name
           print person.age
    • 字符串str的内置方法

      • 字符串是很重要的一种数据类型,今天我们就一起来看str的内在。

        1. 字符串的声明

        myname="ben"
        yourname=str("Jin")
        
        print("myname的值是%s,类型为%s" %(myname,type(myname)))
        print("yourname的值是%s,内部成员为%s" %(yourname,dir(myname)))
        ==========================================
        返回结果:
        myname的值是ben,类型为<class 'str'>
        yourname的值是Jin,内部成员为['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

        2. __init__  构造方法 yourname=str("Jin")生成对象的时候运行的就是__init__

        3.__contains__ 是否包含

        myname="Ben"
        result=myname.__contains__("en")
        print(result)
        ===========================
        返回结果:True

        4.__getattribute__ 反射 无条件被调用,通过实例访问属性。如果class中定义了__getattr__(),则__getattr__()不会被调用(除非显示调用或引发AttributeError异常) 

        5. __getitem__  dic[1]实际执行的就是字典的__getitem__方法

        6. capitalize首字母大小写

        myname="ben"
        result=myname.capitalize()
        print(result)
        ===================================
        运行结果
        Ben

        7. casefold 跟lower类似,讲字符串变成小写,不过不只是针对ASCII,也可以将一些德文之类的变成小写。汉语 & 英语环境下面,继续用 lower()没问题;要处理其它语言且存在大小写情况的时候再用casefold()

        8. center 将字符串居中,并用其他字符包围

        myname="ben"
        result=myname.center(20,"*")
        print(result)
        ===========================
        返回结果:
        ********ben*********

        9. count 计算字符串的一部分出现的次数

        myname="benbenben"
        result=myname.count("ben",2,9)
        print(result)
        =========================
        返回结果:2

        10. endwith 判断是否以某字符串结尾

        myname="benbenben"
        result=myname.endswith("ben",2,9)
        print(result)
        ==============================
        返回结果: True

        11. encode

        myname="陈真"  ##utf8
        result=myname.encode("gbk") ##内部是先转成unicode 然后转成gbk
        print(result)
        =================================
        返回结果:b'xb3xc2xd5xe6'
  2. 流程控制

    • 分支结构if...else...
      • if必须有;else和ifelse可有可没有并且不能单独纯在
      • 格式:条件判断最后加冒号;层次关系要缩进
      • x=input("请输入x的值")
        y=input("请输入y的值")
        
        if x==y:
            print("x=y")
        elif x>y:
            print("x>y")
        else:
            print("x<y")
        
        ========================
        返回结果:
        请输入x的值10
        请输入y的值20
        x<y
      • 条件判断是True的情况
        • 整形非0
        • 其他数据类型非空
        • 函数等看返回值
      • 嵌套
      • 条件判断
        • and or not
    • for循环
      • for i in 序列 ...
      • 序列后面有冒号;层次关系要缩进
      • for ... else ...   else语句只有在for循环中正常结束才会运行,比如当在for循环中有异常(比如control+c)或者执行break或者return退出是不会执行else。
      • 序列包含字符串,列表,字典等等
      • range和xrange: range是直接在内存中生成好列表,xrange是先生成变量,使用迭代的时候才开始创建列表。range(i,j,k)  i:起始数值,默认是0  j:终止数值但不包括在范围内  k:步进值,默认是1
      • print("我们来计算从x一直加到y的和")
        x=input("请输入x的值:")
        y=input("请输入y的值:")
        
        while x>y:
            y=input("x要比y小,请重新输入y的值:")
        
        sum=0
        for i in range(int(x),int(y)+1):
            sum=sum+i;
        
        print("x+y的值",sum)
        
        ======================
        返回结果
        我们来计算从x一直加到y的和
        请输入x的值:1
        请输入y的值:0
        x要比y小,请重新输入y的值:100
        x+y的值 5050
      • 遍历字典
      • ##字典的遍历
        d={'a':1,'b':2,'c':3}
        
        ##获取key
        print("for循环获取key")
        for key in d:
            print(key)
        
        ##获取value
        print("for循环获取value")
        for key in d:
            print(d[key])
        
        ##获取key和value
        print("for循环获取key和value")
        print(d.items()) ##生成元组的列表
        for key,value in d.items():
            print(key,value)
        =================================
        返回结果
        for循环获取key
        b
        a
        c
        for循环获取value
        2
        1
        3
        for循环获取key和value
        dict_items([('b', 2), ('a', 1), ('c', 3)])
        b 2
        a 1
        c 3
    • 循环控制
      • break: 退出当前层次循环
      • continue:继续当前层次循环的下一轮
      • exit():退出脚本
    • while循环
      • while 表达式 ... else  ...   else用法跟for循环一样
      • 应用场景:三级菜单 输入城市序号进入该菜单 输入b返回 输入q退出

        #!/usr/bin/env python3
        
        import os
        import sys
        
        '''
        制作一个三级菜单
        山东
           日照
               东港
               岚山
           五莲
        '''
        
        def showcd(dir):
            '''
            :param dir: 要去的目录
            :return: 返回要去的目录下的列表
            '''
        
            if (os.path.exists(dir)):
                dirlist = os.listdir(dir)
                num = 1
                for dirname in dirlist:
                    print("%s.%s" % (num, dirname))
                    num += 1
                print("请输入b返回或者q退出")
                return dirlist
        
        
        dir = os.getcwd()
        dirlist = showcd(dir)
        
        
        while(True):
            city=input("请输入:")
            if(city=="q"):
                exit(0)
            elif(city=="b"):
                dir=os.path.dirname(dir)
                dirlist=showcd(dir)
            elif(os.listdir(dir+"/"+dirlist[int(city)-1])):
                dir=dir+"/"+dirlist[int(city)-1]
                dirlist = showcd(dir)
            else:
                print("已经没有下级城市")
  3. 函数

    • 函数的名称和格式参数

      • 名称不能使用保留字,也尽量不要使用已有的原生的函数名,因为会覆盖,比如 print input
        • 保留字
        • False      class      finally    is         return
          None       continue   for        lambda     try
          True       def        from       nonlocal   while
          and        del        global     not        with
          as         elif       if         or         yield
          assert     else       import     pass
          break      except     in         raise
      • 函数格式
        • def 函数名(参数列表): 函数体
        • def myTest(a,b):
              c=a+b
              return c
          
          print(myTest(1,2))
          
          #使用已定义的input
          def input(a,b):
              return a+b
          
          print(input(1,2)) 
    • 参数
      • 形式参数(形参)
        • 形参是定义函数的时候参数列表中的参数
      • 实际参数(实参)
        • 实参是函数在使用的时候参数列表的参数
        • 举个例子还说明形参和实参
        • def myTest(a,b): ## a和b是形参
              c=a+b
              return c
          
          m=1
          n=2
          print(myTest(m,n)) ##m和n是实参
      • 默认参数
        • 在参数定义的时候,某些形参可以使用默认的参数值。默认参数的设置是“形参=默认参数值”
        • def myTest(a,b=2): ## a和b是形参 b有默认参数值2
              c=a+b
              return c
          
          print(myTest(1)) ##使用了b的默认参数值
        • 默认参数的设定是从右开始向左,只要某一个参数是默认参数,那么所有右边的形参也都是默认参数。否则将引起混论,不知道所使用的实参对应的到底是哪个形参。比如说定义一个函数myTest(a,b=1,c,d=3), 如果myTest(1,3,4)这样用的话,就不知道b=3,c=4还是c=3,d=4.
        • def myTest(a,b=2): ## a和b是形参 b有默认参数值2
              c=a+b
              return c
          
          print(myTest(1,5)) ##没有使用默认参数值
          print(myTest(1)) ##使用了b的默认参数值
          
          def myTest(a,b=2,c=6): ## a和b是形参 b有默认参数值2 c有默认参数值6
              d=a+b+c
              return d
          
          print(myTest(1,5)) ##a=1 b=5 c=6
          print(myTest(1,c=5)) ##a=1 b=2 c=5
          
          def myTest(a,b=1,c,d=3): ## 会报错:SyntaxError: non-default argument follows default argument
              e=a+b+c+d
              return e
      • 实际参数列表是元组tuple

        • 已定义函数的形参列表并不是元组,却想把某元组作为实参传入该函数
        • 格式 t=(1,2);  fun(*t)
        • 元组的元素的个数跟函数形参的个数要一致,不能多也不能少
        • def fun(name,age):
              print('name: %s age:%d' %(name,age))
          
          t=('Ben',20)
          
          fun(*t)
          
          ==========================
          返回结果
          name: Ben age:20
      • 实际参数列表是字典dict
        • 已定义函数的形参列表并不是字典,却想把某字典作为实参传入该函数
        • 格式 d={‘key’:1,'value':2};  fun(**d)
        • 字典的元素的key和个数跟函数形参的名称和个数要一致,不能多也不能少
        • def fun(name,age):
              print('name: %s age:%d' %(name,age))
          
          d={'name':'ben','age':20}
          
          fun(**d)
      • 形式参数接受不确定个数的参数(元组或者字典)
        • 在形参中加入类似*args的参数,可以在使用的时候接收多余的实际参数
        • 在形参中加入类似**kwargs的参数,可以在使用的时候接收多余的key=value的实际参数
        • 在同时加入*args 和 **kwargs的时候,必须按照类型的顺序, 不能反了或者有交叉
        • def fun(name,age,*args,**kwargs):
              print('name: %s age:%d' %(name,age))
              print(args)
              print(kwargs)
          
          fun(1,2,3,key=1,v=2) #1->name 2->age 3->args key=1->**kwargs v=2->**kwargs
          
          ==============================
          返回结果
          name: 1 age:2
          (3,)
          {'key': 1, 'v': 2} 
    •  返回值
      • 使用return来指定返回值,并终止函数
      • 默认情况下,也就是不带return的函数,返回值是None
      • print的内容不是返回值
      • def fun(name,age):
            print('name: %s age:%d' %(name,age))
            if(age<10):
                return "小学生"
            if(age<20):
                return "中学生"
            if(age<30):
                return "大学生"
            return "工作者"
        
        s=fun("ben",30)
        print('*'*10)
        print(s)
        
        ================================
        返回结果
        name: ben age:30
        **********
        工作者
    • 作用域
      • 全局变量:函数之外定义的变量,任何地方都可以调用
      • 局部变量:函数内部定义的变量,只能在函数体内使用
      • 当局部变量和全局变量重名的时候,在函数体内按照执行顺序的原则,在定义前使用的是全局变量,在定义后使用的是局部变量。
      • 在函数体内可以用global来定义全局变量
      • age=30 #全局变量
        
        def fun(age):
            print(age) #使用的是全局变量
            age=19 #局部变量
            print(age) #使用的是局部变量
        
            global name #先定义后使用
            name='Ben'
        
        
        fun(age)
        print(age) #局部变量的赋值不会影响全局变量
        print(name)
        
        ===============================
        返回结果
        30
        19
        30
        Ben
    • 递归和lambda
      • lambda是匿名函数,有些时候没有必要定义函数的名称来直接使用,比如在特殊函数filter map reduce(reduce在python3.0移除到内置函数之外了) 这些函数的特点是需要以其他函数为输入。
      • i=10
        
        #使用递归
        def f(x):
            if(x==1):
                return 1
            return x*f(x-1)
        
        print("使用递归的结果:",f(i))
        
        #使用reduce+lambda
        from functools import reduce
        print("使用reduce的结果:",reduce(lambda x,y:x*y,range(1,i+1)))
        
        ==========================================
        返回结果
        使用递归的结果: 3628800
        使用reduce的结果: 3628800
      • 实现switch功能,python里面本身没有switch,可以通过使用字典和lambda来帮助实现switch的功能

      • ##计算器
        
        from __future__ import division
        
        def result(x,y):
            return {
                    '+':x+y,
                    '-':x-y,
                    '*':x*y,
                    '/':x/y
            }
        
        a=4
        b=6
        o='/'
        print("%s%s%s的结果:%s" % (a,o,b,result(a,b).get(o)))
        ===================================
        返回结果
        4/6的结果:0.6666666666666666
    • 内置函数
      • print(dir(__builtins__))
        ==================
        [
        'abs', 'all', 'any', 'ascii', 
        'bin', 'bool', 'bytearray', 'bytes',
        'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',
        'delattr', 'dict', 'dir', 'divmod', 
        'enumerate', 'eval', 'exec', 'exit',
        'filter', 'float', 'format', 'frozenset',
        'getattr', 'globals',
        'hasattr', 'hash', 'help', 'hex',
        'id', 'input', 'int', 'isinstance', 'issubclass', 'iter',
        'len', 'license', 'list', 'locals',
        'map', 'max', 'memoryview', 'min',
        'next',
        'object', 'oct', 'open', 'ord',
        'pow', 'print', 'property',
        'quit',
        'range', 'repr', 'reversed', 'round',
        'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
        'tuple', 'type',
        'vars',
        'zip'
        ]
  4. 正则表达式 (学习中)

    • 包和基本函数
      • 包 import re
      • findall 搜索
      • import re
        s=r'a'
        r=re.findall(s,'aaa')
        print(r)
        ==============
        返回结果
        ['a', 'a', 'a']
      • compile 可以把正则表达式编译成一个正则表达式对象
      • import re
        s=r'a'
        t=re.compile(s)
        r=t.findall('aaa')
        print(r)
        ==========
        返回结果
        ['a', 'a', 'a']
      • match 正则匹配从开头开始匹配
      • import re
        s=r'a'
        t=re.compile(s)
        r=t.match('aaa')
        print(r)
        r=t.match('baaa')
        print(r)
        ==============
        返回结果
        <_sre.SRE_Match object; span=(0, 1), match='a'>
        None
      • search 正则匹配从任何地方开始匹配
      • import re
        s=r'a'
        t=re.compile(s)
        r=t.search('aaa')
        print(r)
        r=t.search('baaa')
        print(r)
        ===================
        返回结果
        <_sre.SRE_Match object; span=(0, 1), match='a'>
        <_sre.SRE_Match object; span=(1, 2), match='a'>
      • finditer正则匹配生成迭代对象
      • import re
        s=r'a'
        t=re.compile(s)
        for i in t.finditer('aaa'):
            print(i)
            print(i.group())
        ====================
        返回结果
        <_sre.SRE_Match object; span=(0, 1), match='a'>
        a
        <_sre.SRE_Match object; span=(1, 2), match='a'>
        a
        <_sre.SRE_Match object; span=(2, 3), match='a'>
        a
      • sub替换字符串中的匹配项
      • import re
        s=r'a'
        t=re.compile(s)
        r=t.sub('x','aba')
        print(r)
        ====================
        返回结果
        xbx
      • split分割字符串
      • import re
        s=r'a'
        t=re.compile(s)
        r=t.split('xaba')
        print(r)
        ==============
        返回结果
        ['x', 'b', '']
    • 元字符
      • .  单个任意字符
      • import re
        s=r'.a'
        t=re.compile(s)
        r=t.findall('xaba')
        print(r)
        =================
        返回结果
        ['xa', 'ba'
      • ^ 以后面的字母作为开头,或者在[]里面的时候放在开头表示取反,其他位置就代表是普通字符^
      • import re
        s=r'^a'
        t=re.compile(s)
        r=t.findall('aba')
        print(r)
        
        s=r'[^a]'
        t=re.compile(s)
        r=t.findall('aba')
        print(r)
        
        s=r'[a^]'
        t=re.compile(s)
        r=t.findall('aba^')
        print(r)
        ================
        返回结果
        ['a']
        ['b']
        ['a', 'a', '^']
      • $ 以前面的字符作为结尾 或者在[]里面代表普通字符
      • import re
        s=r'a$'
        t=re.compile(s)
        r=t.findall('aba')
        print(r)
        
        s=r'[$a]'
        t=re.compile(s)
        r=t.findall('aba$')
        print(r)
        
        s=r'[a$]'
        t=re.compile(s)
        r=t.findall('aba$')
        print(r)
        ===================
        返回结果
        ['a']
        ['a', 'a', '$']
        ['a', 'a', '$']
      • *代表任意个前面的字符,属于贪婪的匹配,取消贪婪要加?
      • import re
        s=r'ab*b'
        t=re.compile(s)
        r=t.findall('abbbbb')
        print(r)
        
        s=r'ab*?b'
        t=re.compile(s)
        r=t.findall('abbbbb')
        print(r)
        ==================
        返回结果
        ['abbbbb']
        ['ab']
      • + 至少一次
      • import re
        s=r'ab+b'
        t=re.compile(s)
        r=t.findall('abbbbb')
        print(r)
        
        s=r'ab+?b'
        t=re.compile(s)
        r=t.findall('abbbbb')
        print(r)
        =================
        返回结果
        ['abbbbb']
        ['abb']
      • ? 0或者1次
      • import re
        s=r'ab?'
        t=re.compile(s)
        r=t.findall('abbbbb')
        print(r)
        ===============
        返回结果
        ['ab']
      • [] 集合 匹配集合里面的任意字符即可取出
      • import re
        s=r'[ab]'
        t=re.compile(s)
        r=t.findall('abbbbb')
        print(r)
        ===================
        返回结果
        ['a', 'b', 'b', 'b', 'b', 'b']
      • {} 重复次数
      • import re
        s=r'[ab]{2}'
        t=re.compile(s)
        r=t.findall('abbbbb')
        print(r)
        ===============
        返回结果
        ['ab', 'bb', 'bb']
      • () 组合 跟|配合是或者 跟findall配合是取出()匹配的部分
      • import re
        s=r'(ab|bc)'
        t=re.compile(s)
        r=t.findall('ababbbbab')
        print(r)
        
        s=r'(ab|bc)(ab|bc)'
        t=re.compile(s)
        r=t.findall('ababbbbab')
        print(r)
        
        s=r'(ab|bc){2}'
        t=re.compile(s)
        r=t.findall('ababbbbab')
        print(r)
        ======================
        返回结果
        ['ab', 'ab', 'ab']
        [('ab', 'ab')]
        ['ab']
      • 转义
      • d D 数据
      • w W 字母
      • s S 空格
      • ##小爬虫
        import re import urllib.request def gethtml(url): page
        = urllib.request.urlopen(url) html = page.read() html = html.decode('utf-8') return html def downloadimg(result): x=0 for img in result: file = "%d.%s" %(x,img[1]) print(file) urllib.request.urlretrieve(img[0],file) x = x+1 url ="http://itest.info/courses/2" html = gethtml(url) rs = r"img .*? src="(http.*?(png|jpg))" result = re.findall(rs,html) downloadimg(result)
    • 编译标志
      • S - Dotall
      • I - Ignorecase
      • L - Locale
      • M - Multiline
      • X - Verbose

基础的学习差不多啦 也有一个月了 接下来有空开始高级一点的啦~ 加油~

原文地址:https://www.cnblogs.com/benchen/p/6032850.html