天天看點

Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

變量

注釋

#行注釋

‘’’

‘’'塊注釋

變量定義

命名

數字、大小寫、下劃線 #中文也可以

數字不開頭、下劃線開頭有特殊含義、大小寫敏感

使用固定含義英文單詞或縮寫,POSIX命名規則

駝峰命名法:第一個字母大寫(類名)、隻第一個單詞的第一個字母小寫(類中的命名)、單詞間下劃線

避開:保留字、關鍵字

#檢視關鍵字
import keyword#引入關鍵字子產品
#列印出系統關鍵字
print(keyword.kwlist)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#定義變量age,把18放入變量age中
age = 18
print(age)
print(18)

#給age1,age2,age3放入同樣一個内容或值
age1 = age2 = age3 = 18
print(age1)
print(age2)
print(age3)

#一行内給多個變量指派
age4,age5,age6=12,21,45
print(age4)
print(age5)
print(age6)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

Linux下輸入jupyter notebook啟動

Esc為指令模式

Esc後a為向上建立輸入行b為向下建立輸入行

Esc後m為markdown筆記模式

Ctrl+Enter運作且不建立

Shift+Enter運作且建立

變量類型

标準資料類型六種

數字Number

字元串類型str

清單list

元組tuple

字典diet

集合set

數字類型Number

無大小限制

常見數字分類:

  • 整數

    二進制以0b開頭

    八進制以0o開頭

    十六進制0x開頭

  • 浮點數

    3.就是3.0

    .4就是0.4

  • 科學計數法

    數字+e+數字(10的幂)

  • 複數

    虛部用j/J表示

  • 布爾值

    真假值 True/False

    當數字使用True=1,False=0

    數字當布爾值使用0=False,其他=True

字元串類型str

  • 引号引起的一段内容

    單引号雙引号意思一緻

    三引号表示多行資訊

None類型

  • 表示沒有,占位
  • 傳回空

表達式

  • 通常傳回一個結果
  • 數字 變量 運算符

運算符

  • 運算符分類

    算數運算符

    比較或關系運算符

    指派運算符

    邏輯運算符

    位運算

    成員運算符

    身份運算符

算數運算符

pyhton無自增自減運算符

#算數運算符
#加減乘除基本一緻
a7 = 8 - 1
a8 = 8 * 8
a9 = 8 + 1
print(a7)
print(a8)
print(a9)
#python除法分為普通除法,地闆除,取餘
#正常除法
a10 = 9 / 4
print(a10)
#地闆除
a11 = 9 // 4
print(a11)
#取餘
a12 = 9 % 4
print(a12)
#指數
a13 = 6 ** 3
print(a13)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

比較運算符

  • 兩個内容比較
  • 結果是布爾值True/False
#等于 ==
a = 3 == 4
print(a)
#不等于 !=
a = 3 !=4
print(a)
#>,>=
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

指派運算符

# 指派符号 =
a = 9
# 複雜指派
a = b =9
a,b = 1,2
print(a)
#指派縮寫 運算符加= 無自增自減
a = a + 3
print(a)
#+=無含義
a += 3
print(a)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

邏輯運算符

  • 布爾類型或值進行運算

    and: 邏輯與 or: 邏輯或 not:邏輯非

    Python無異或

    and乘,or加,not取反

    真1假0

  • 邏輯運算的短路問題

成員運算符

  • 檢測值或變量是否在某個集合中

    in:成員運算符

    not in:不在

#in案例
L = [1,2,3,4,5]
a = 6
aa = a in L
print(aa)
aa = a not in L
print(aa)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

身份運算符

  • 确定兩個變量是否為同一變量

    is:變量運算符

    is not:不是

#身份運算符
a = 1
b = 10000393
aa = a is b
print(aa)
#值相同,不是同一變量
a = 10000393
b = 10000393
aa = a is b
print(aa)
#小的數字,具有自己記憶體,不需新空間-5~256之間
a = 5
b = 5
aa = a is b
print(aa)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

運算優先級

小括号最高優先級 **最高 位運算翻轉 乘除 加減 位運算 比較 指派 身份 成員 邏輯

程式結構

  • 程式三種結構

    順序 循環 分支

分支結構

  • 分支結構基本文法

    if 條件表達式:

    語句1

    語句2

    語句3

    語句塊

  • 條件表達式

    計算結果必須是布爾值的表達式

    冒号不能少

    if後的語句,屬于if語句塊,同一個縮進等級

    執行True後的if縮進語句塊

  • if語句可以嵌套

    Python沒有switch

雙向分支

  • if…else…

    文法結構:

    if 表達式:

    語句1

    語句2

    ···

    else:

    語句1

    語句2

    ···

  • input的作用

    input的輸入為字元串類型

#input接收輸入并把内容傳回變量
gender = input("請輸入性别")
print(gender)
if gender == "man":
    print("哼")
else:
    print("開心")
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#輸入考試成績
#90以上優秀,80~90良,70~80中,60~70平,60以下不及格
score = input("請輸入成績")
#輸入為字元串
score = int(score)
if score >= 90:
    print("優秀")
if score >= 80 and score < 90:
    print("良")
if score >= 70 and score < 80:
    print("中")
if score >= 60 and score < 70:
    print("平")
if score < 60:
    print("不及格")
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

多路分支

  • 結構

    if 條件表達式:

    語句1

    ···

    elif 條件表達式:

    語句1

    ···

    else

    語句1

    ···

    else可選

#輸入考試成績
#90以上優秀,80~90良,70~80中,60~70平,60以下不及格
score = input("請輸入成績")
#輸入為字元串
score = int(score)
if score >= 90:
    print("優秀")
elif score >= 80:
    print("良")
elif score >= 70:
    print("中")
elif score >= 60:
    print("平")
else:
    print("不及格")
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

循環語句

  • 分類

    for while

for循環

  • 文法

    for 變量 in 序列:

    語句1

    語句2

    ···

#[1,2,3,4,5,6,7]循環列印
list_one = [1,2,3,4,5,6,7]
for num in list_one:
    print(num)
    print(num+100)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
  • for-else語句

    else可選

list_stu = ['a','b','c']
for stu in list_stu:
    if stu == "c":
        print("right")
    else:
        print("wrong")
else:
    print("end")
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
  • break continue pass

    break:結束

    continue:繼續

    pass:占位符,沒有跳過功能

#尋找數字,找到列印,并結束
list_num = [1,2,34,7,5,2,6,7,4,3]
for num in list_num:
    if num == 7:
        print("find")
        break
    else:
        print(num)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#1~10,找到并列印偶數
list_num = [1,2,3,4,5,6,7,8,9,10]
'''
for num in list_num:
    if num % 2 == 0:
        print(num)
        print("偶數")
    else:
        continue
'''
for num in list_num:
    if num % 2 == 1:
        continue
    print(num)
    print("偶數")
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

range函數

  • 生成有序數列

    生成數字隊列可以定制

    range生成序列左包括,右不包括

    randint特例

list_num = range(1,3)
for num in list_num:
    print(num)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

while循環

  • 條件成立就循環,不知道具體循環次數,
  • while文法:

    while 條件表達式:

    語句塊1

    else:

    語句塊2

    else可選

#年利率6.7%,本利每年翻滾,多少年後本錢翻倍
benqian = 10000
year = 0#存放需要翻本的年數
while benqian < 20000:
    benqian = benqian * (1 + 0.067)
    year += 1
print(year)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

函數

  • 代碼的一種組織形式
  • 函數應該完成一項特定的工作,一般一個函數隻能完成一項工作
  • 函數的使用

    首先定義

    使用函數,即調用函數

#定義函數,def關鍵字,小括号冒号
def func():
    print("biubiu")
    print("happy")
print("begin")
#調用函數,小括号不能省
func()
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

函數的參數和傳回值

  • 參數:給函數傳遞必要資料或資訊

    形參(形式參數):函數定義時使用,無具體值,占位符

    實參(實際參數):調用函數時輸入的值

  • 傳回值:調用函數的執行結果

    使用return傳回結果

    沒有傳回值,使用return None表示結束,推薦使用

    執行return,立即結束

    沒有return關鍵字,預設傳回None

def hello(person):
    print("{0},hi".format(person))
    print("{},haaa".format(person))

p = "xiao"
#調用函數,p為實參
hello(p)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#九九乘法表
for o in range(1,10):#外循環,1~9
    for i in range(1,o+1):#内循環,從1開始,列印到行數相同的數量
        print(o * i,end=" ") #每一次輸出都以空格結束
    print()#每層輸出預設換行
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#函數 九九乘法表
def jiujiu():
    for o in range(1,10):
        for i in range(1,o+1):
            print(o * i,end=" ") 
        print() a
    return None
jiujiu()     
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#函數改造
def printLine(line_num):
    '''
    line_num:行号
    列印一行九九乘法表
    '''
    for i in range(1,line_num + 1):
        print(line_num * i,end=" ")
    print()
    
def jiujiu():
    for o in range(1,10):
        printLine(o)
    return None
jiujiu()
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

參數詳解

  • 參數分類

    普通參數/位置參數

    預設參數

    關鍵字參數

    收集參數

#普通參數
def normal_para(one,two,three):
    print(one + two)
    return None
normal_para(1,2,3)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#預設參數
def default_para(one,two,three=100):
    print(one + two)
    print(three)
    return None
default_para(1,2)  
default_para(1,2,3)  
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#關鍵字參數
def keys_para(one,two,three):
    print(one + two)
    print(three)
    return None
keys_para(one=1,two=2,three=30)
keys_para(three=30,one=1,two=2)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
  • python内置類型:str list tuple set dict

str字元串

  • 轉義字元 格式化 内建函數

字元串

  • 文字資訊

    單引号、雙引号、三引号(多行)

轉義字元

  • 用一個特色方法表示不友善寫出的内容,回車,換行,倒退等

    借助反斜杠\後的一個或幾個字元轉義

    單個反斜杠表示此行未結束,下一行繼續

    Windows:\n

    Linux:\r\n

    Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#轉義 Let's Go
s = 'Let\'s Go'
print(s)
#使用單雙引号嵌套
s = "Let's Go"
print(s)
#表示斜杠 路徑c:\User\GGGG
s = "c:\\User\\GGGG"
print(s)
#回車換行
s = "biubiu\nyooooo\ndiu"
print(s)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

格式化

  • 把字元串按一定格式列印或填充
  • 格式化分類

    傳統格式化

    format

傳統格式化

  • 使用%進行格式化,%(占位符)

    占位符可單獨使用

    格式化資訊多于一個,需要括号括起

    %.2f表示小數後幾位

%d, %i,代表整數,%f-浮點,%s,字元串,%c,char. %p 指針,%fL 長long,%e科學計數,%g 小數或科學計數。

C語言中的格式占位符:

%a,%A 讀入一個浮點值(僅C99有效)

%c 讀入一個字元

%d 讀入十進制整數

%i 讀入十進制,八進制,十六進制整數

%o 讀入八進制整數

%x,%X 讀入十六進制整數

%s 讀入一個字元串,遇空格、制表符或換行符結束。

%f,%F,%e,%E,%g,%G 用來輸入實數,可以用小數形式或指數形式輸入。

%p 讀入一個指針

%u 讀入一個無符号十進制整數

%n 至此已讀入值的等價字元數

%[] 掃描字元集合

%% 讀%符号

#填充
s = "b iubiu"
print(s)
s = "d iubiu"
print(s)
s = "p iubiu"
print(s)

#%s 簡單字元串
s = "%s iubiu"
print(s)
print(s%"b")
print(s%"p")
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

format格式化

  • 使用函數形式進行格式化,代替%

    {:.2f}小數點後位數

#不用指定位置,按順序讀取
s = "{} {}!"
print(s.format("biu","piu"))

s = "{} {}!".format("biu","piu")
print(s)

#設定指定位置
s = "{1} {0}!".format("biu","piu")
print(s)

s = "{0} {0}!".format("biu")
print(s)

#使用命名參數
s = "i {biu},you {diu},everyone {piu}"
s = s.format(biu="木啊",diu="木木",piu="啊啊")
print(s)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#通過字典設定參數,解包**
#使用命名參數
s = "i {biu},you {diu},everyone {piu}"
s_dict = {"biu":"木啊","diu":"木木","piu":"啊啊"}
s = s.format(**s_dict)
print(s)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

str内置函數

  • python使用str代表字元串

查找類函數

字元串查找類,find,index,islower
	find:查找字元串中是否包含一個子串
	index:找不到與find有差別
	rfind,lfind:從左從右查找/沒看到左查找
           
s = "biu piu piu diu diu biu"
s1 = "piu"
#傳回第一次發現這個字元串的位置
s.find(s1)
#傳回-1表沒有找到
s2 = "yiu"
s.find(s2)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#找不到會報錯或引發異常
s.index(s2)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#可以使用區間
s = "biu piu piu diu diu biu"
s1 = "piu"
#從第五個開始找
s.find(s1,6)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

判斷類函數

  • 一般以is開頭

    isalpha:判斷是否字母

    至少一個字元

    漢字是alpha,區分中英文一般使用unicode

    isdigit,isnumeric,isdecimal:判斷數字

    一般不使用,采用正規表達式的方式判斷

    isdigit()

    True: Unicode數字,byte數字(單位元組),全角數字(雙位元組),羅馬數字

    False: 漢字數字

    Error: 無

    isdecimal()
      True: Unicode數字,,全角數字(雙位元組)
      False: 羅馬數字,漢字數字
      Error: byte數字(單位元組)
      
      isnumeric()
      True: Unicode數字,全角數字(雙位元組),羅馬數字,漢字數字
      False: 無
      Error: byte數字(單位元組)
               
s1 = "biu biu"
s2 = "pipi"
print(s1.isalpha())
print(s2.isalpha())
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

内容判斷類

  • startswitch/endswith:是否以XXX開頭或結尾

    檢測某個字元串是否以某個子串開頭

    suffix:被檢查的字元串,必須有

    start:檢查範圍的開始範圍

    end:檢查範圍的結束範圍

  • islower/isupper:判斷字元串是否小寫,大寫

    漢子字元串無大小寫概念

diu = "diu"
biu = "biu"
s = "diu piu biu"
print(s.startswith(diu))
print(s.endswith(biu))
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
s1 = "Biu piu diu"
s2 = "Biupiudiu"
s3 = "biupiudiu"
s4 = "biu piu diu"
s5 = "麼麼"
print(s1.islower())
print(s2.islower())
print(s3.islower())
print(s4.islower())
print(s5.islower())
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

操作類函數

format:格式化

strip:删除字元串兩邊空格,預設空格,可指定删除,删除符合條件的連續字元

join:字元串拼接

s = "BBBBiu diu piu   "
print(s.strip(),end='----')
print()
print(s.strip('B'),end='----')
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#字元串作為分隔符将内容拼接
s1 = "^"
s2 = "@"
s3 = " "
s = ["biu","piu","diu"]
print(s1.join(s))
print(s2.join(s))
print(s3.join(s))
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

list清單

  • 一組由有序資料組成的序列

    資料有先後資料

    資料可以不是一類資料

  • list建立

    直接建立,用中括号,内容用英文逗号隔開

    使用list建立

    清單包含單個字元串為特例

L1 = [1,2,3,4,5]
L2 = [1,2,3,"biu","piu"]
print(L1)
print(L2)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
L3 = list()
print(L3)
print( type(L3) )
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
  • 内置函數

    help:幫助函數

    type:顯示變量類型

    id:顯示變量id

    print:

#list建立的特例
s = "biu piu"
L1 = [s]
print(type(L1))
print(L1)
s = "biu piu"
L1 = list(s)
print(type(L1))
print(L1)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

清單常見操作

  • 通路

    使用下标操作,也叫索引

    清單的元素索引從0開始,indexError為超标

  • 切片操作

    對清單進行任意一段的截取

    截取之後建立一個新的清單

    下标可超出範圍,超出後不再考慮下标内容

    下标為負數,表示從右往左,最後一個數字的下标是-1

L1 = [23,3,4,54,3]
print(L1[1])
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#切片操作需要注意取值範圍,左包括右不包括
L1 = [10,20,30,40,50,60,70,80,90,100]
print(L1[1:6])
#切片後全新清單
L2 = L1[0:10]
print(id(L1))
print(id(L2))
#切片下标可以為空
print(L1[:4])
print(L1[6:])
print(L1[:])
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
print(L1[:])
print(L1[::1])
print(L1[::2])
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#預設從左向右
print(L1[-2:-5])
print(L1[-2:-5:-1])
print(L1[-4:-1])
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

tuple(元組)

  • 不允許改變的清單

    有序

    可以通路,不可以被修改

    元素可以是任意類型

#直接使用小括号
ta = ()
print(type(ta))
#當使用小括号建立一個元素的tuple時
tb = (100)
print(type(tb))
tc = (100,)
print(type(tc))
td = (100,200,300)
print(type(td))
print(td)
#直接用逗号
ta = 100,
print(type(ta))
tb = 200,300,400#200,300,400,
print(type(tb))
#使用定義
ta = tuple()
print(ta)
li = [1,2,3,"biu"]
tb = tuple(li)#tuple參數可疊代
print(tb)
print(li)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#tuple的索引操作
la = ["biu","diu","piu"]
print(la)
ta = tuple(la)
print(ta[2])
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#tuple分片操作
print(ta[:])
print(ta[:2])
print(ta[-1::-1])
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#元組相加
ta = 100,200,300
tb = ("biu","diu","piu")
tc = ta + tb
print(tc)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#tuple乘法
tc = tb * 2
print(tc)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#tuple成員檢測
print(tb)
if "biu" in tb:
    print("right")
if "diu" not in tb:
    print("not")
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#元組周遊
for i in tb:
    print(i)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
ta = ((10,20,30),("biu","diu","piu"),(100,200,300))
for i in ta:
    print(i)
    for j in i:
        print(j)
#i,j,k 要和元組的元素個數對應
for i,j,k in ta:
    print(i,j,k)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#常用元組函數
ta = (1,43,5,6,7,87)
#len:長度
print(len(ta))
#max:最大值
print(max(ta))
#數字字元串不能比較
tb = (1,2,3,"love")
print(max(tb))
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#count:對某一進制素計數
ta = (1,3,5,3,1,4,7,1,54)
print(ta.count(1))
#index:某一進制素所在位置
print(ta.index(1))
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#tuple特殊用法 a,b呼喚
a = 100
b = "biu"
print(a,b)
a, b = b, a
print(a,b)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

集合

  • 數學定義 内容無序且内容不重複
  • frozenset 冰凍集合

    不允許修改的集合

#集合的定義
#使用set關鍵字
sa = set()
print(sa)
print(type(sa))

li = [1,2,3,4,5,6,7,8,9,2,3]
sb = set(li)
print(sb)
#使用大括号
sc = {1,2,3,4,2,3,4}
print(sc)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#in 操作
if 2 in sc:
    print(222)
if 23 in sc:
    print(23)
for i in sc:
    print(i)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
sa = {(1,2,3),(4,5,6),("biu","diu","piu")}
for i,j,k in sa:
    print(i,j,k)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#集合的生成式
sa = {1,2,3,4,5,6,7,8,9,10}
sb = {i for i in sa}
print(sb)

sc = {i for i in sa if i % 2 == 0}
print(sc)

#雙重for循環,把sa中的元素平方
#用一個for
sd = { i**2 for i in sa}
print(sd)
#使用兩個for
se = { m*n for m in sa for n in sa}
print(se)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#集合内置函數
#len:長度
print(len(se))
#max/min:最值
#add:向集合中添加元素
sa = {1,2,3,4,5,6,5,4,3,2,1}
print(sa)
print(sa.add(7))
print(sa)
#clear:清空
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
# 删除操作
# remove 和 discard
sa = {1,2,3,4,5,6,7,5,4}
print(sa)
sa.remove(5)
print(sa)
# remove删除的值若不在集合中,報錯
sa.remove(5)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
sa = {1,2,3,4,5,6,7,5,4}
print(sa)
sa.discard(5)
print(sa)
sa.discard(5)
print(sa)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
# pop彈出集合的一個内容,删除的内容是随機的
sa = {1,2,3,4,5,6,7,5,4}
print(sa)
sa.pop()
print(sa)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
# 集合的數學操作
# intersection:交集
sa = {1,2,3,4,5,6}
sb = {4,5,6,7,8,9}
print(sa.intersection(sb))
# difference:差集
print(sa.difference(sb))
print(sa - sb)
# union:并集
print(sa.union(sb))
print(sa + sb)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#frozenset冰凍集合
print(sa)
sb = frozenset(sa)
print(sb)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

遞歸函數

  • 函數直接或間接調用自己
  • 遞歸兩個過程

    往下調用,分解的過程

    往上回溯,綜合的過程

    一定要有結束的條件

def funa(n ):
    print("biu")
    
def funcb(n):
    funa(100)
    print("diu")

funcb(100)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
def fun_a(n):
    print(n)
    if n == 1:
        return 1
    return n * fun_a(n-1)
rst = fun_a(5)
print("f(5)=",rst)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#遞歸必須有結束條件,否則會死循環
def fun_b(n):
    print(n)
    return n * fun_b(n-1)
fun_b(3)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
# 菲比那契數列
def fib(n):
    if n == 1 or n == 2:
        return 1
    return fib(n-1) + fib(n-2)
rst = fib(10)
print("rst = ",rst)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#漢諾塔
a = "A"
b = "B"
c = "C"
def hano(a,b,c,n):
    if n == 1:
        print("{}-->{}".format(a,c))
        return None
    if n == 2:
        print("{}-->{}".format(a,c))
        print("{}-->{}".format(a,b))
        print("{}-->{}".format(b,c))
        return None
    hano(a,c,b,n-1)
    print("{}-->{}".format(a,c))
    hano(b,a,c,n-1)
           

多打了一句,沒影響,最後一句

Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

怎麼感覺不對勁啊,應該是先A到B,最後一個盤子A到C吧????

#漢諾塔
a = "A"
b = "B"
c = "C"
def hano(a,b,c,n):
    if n == 1:
        print("{}-->{}".format(a,c))
        return None
    if n == 2:
        print("{}-->{}".format(a,b))
        print("{}-->{}".format(a,c))
        print("{}-->{}".format(b,c))
        return None
    hano(a,c,b,n-1)
    print("{}-->{}".format(a,c))
    hano(b,a,c,n-1)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

OOP

  • 思想

    以子產品化思想解決工程問題

    面向過程 VS 面向對象

    由面向過程轉向面向對象

  • 常用名詞

    OO:面向對象

    ooa:分析

    ood:設計

    oop:程式設計

    ooI:實作

    類 VS 對象 is-a

    類:抽象,描述的是一個集合,側重于共性

    對象:具象,描述的是個體

    類的内容:

    動作,函數

    屬性,變量

  • 定義類:class關鍵字

    類命名:

    遵循大駝峰

    第一個字母大寫

#定義類
class Student():
    pass
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
#定義一個對象
biu = Student()
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP
class PythonStudent():
    name = "NoOne"
    age = 18
    course = "python"
    
    def GiveMeLove(self):#定義類中的函數需要self關鍵字
        print("Show Love")
        return None
    
biu = PythonStudent()
print(biu.name)
print(biu.age)
print(biu.course)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

self

  • self可以用别的名稱代替,不是關鍵字

    作用為指代本身

class Student():
    name = "diu"
    age = 119
    
    def sayHi(self):
        print("hhhhhhha")
        return None

#self舉例
#執行個體調用函數
piu = Student()
#piu打招呼,不用調用參數,預設執行個體作為第一個參數傳入
piu.sayHi()
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

類的變量作用域的問題

  • 類變量:屬于類自己的變量
  • 執行個體變量:屬于執行個體的變量

    通路執行個體的屬性,如果執行個體沒有定義屬性,則自動通路類的屬性,如果類也沒有定義,報錯

class Student2():
    #name,age是類的變量,不需要字首
    name = "diu"
    age = 119
    
    def sayHi(self,n,a):
        self.name = n
        self.age = a
        print("My name is {},i am {} years old".format(self.name,self.age))
        return None
a = Student2()
a.sayHi("a",17)
print("My name is {},i am {} years old".format(Student2.name,Student2.age))        
print("My name is {},i am {} years old".format(a.name,a.age))        
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

通路類的屬性

  • 在類裡強制通路類的屬性,需要使用__class__(前後兩個下劃線)

    類方法:定義類的方法時,沒有self參數

    特殊的類,例如sos需要直接調用class後的屬性,不能用執行個體調用

    類的方法中 隻允許使用累的内容

    兩種使用方法:ClassName;class

class Student():
    #name,age是類的變量,不需要字首
    name = "diu"
    age = 119
    
    def sayHi(self):
        print("My name is {},i am {} years old".format(self.name,self.age))
        return None
    #sayHai是類的方法,通路類的變量
    def sayHai():
        print("My name is {},i am {} years old".format(self.name,self.age))
        return None
    def sos():
        print("My name is {},i am {} years old".format(Student.name,__class__.age))
        return None

s = Student()
s.sayHi()
Student.sos()
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

構造函數

  • 類在執行個體化時,執行一些基礎性的初始化工作

    使用特殊的名稱和寫法

    在執行個體化時,自動執行

    實在執行個體化時,第一個被執行的函數

    第一個參數必須有,一般使用self

class Student():
    name = "NoName"
    age = 0
    
    def __init__(self):
        print("i am gouzao")
        
a = Student()
print("-----")
print(a.name)
print(a.age)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

面向對象三大特征

  • 繼承 封裝 多态

繼承

  • 子類可以使用父類定義的内容或者行為等

    繼承的實作

    分類,基類,超類,Base Class,super Class

    所有類都必須有一個父類

    預設為object的子類

    子類可以有多個父類

class Person1():
    pass
class Person2(object):
    pass

class Person():
    name = "NoName"
    age = 0
class Teacher(Person):
    pass

t = Teacher()
print(t.name)

class Bird():
    fly = "i can"
    def flying(self):
        print("fly~~~~~~~")
        
class BirdMan(Person,Bird):
    pass

bm = BirdMan()
bm.flying()
print(bm.name)
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

issubclass

  • 檢測是否是子類
  • 檢測兩個類的父子關系
print(issubclass(BirdMan,Bird))
print(issubclass(BirdMan,Person))
print(issubclass(BirdMan,Teacher))
           
Python之旅基礎文法變量表達式程式結構函數str字元串list清單tuple(元組)集合遞歸函數OOP

構造函數的繼承

  • 預設繼承
上一篇: Android的Log
下一篇: Ant 基礎學習

繼續閱讀