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'\xb3\xc2\xd5\xe6'
  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

 

基礎的學習差不多啦 也有一個月了 接下來有空開始高級一點的啦~ 加油~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM