天天看點

python期末考試重點_Python期末複習筆記

本篇根據老師畫的重點基本上将期末考點都囊括了

如果發現有錯誤或遺漏歡迎各位在學習群裡指正

可能看起來稍微有點多,但其實大部分都是代碼

所有代碼塊都可以直接粘到編譯器裡執行,會報錯的代碼我都加了注釋

(ง •_•)ง,加油

Python 語言基礎

python規範

命名規則

必須以下劃線或字母開頭

前後單下劃線為系統變量

雙下劃線開頭為類的私有變量

關鍵字不能用作變量名

注釋

單行注釋以 # 開頭

多行注釋可用多個 # 或者用 三引号(文檔注釋)

多行語句

行尾使用反斜線(\)來續行

同一行寫多條語句

語句間用分号(;)分隔

輸入輸出

輸出print()

print預設在末尾換行

a = 1

b = 2

c = 3

# 直接輸出多個變量

print(a,b,c) # 輸出:1 2 3

# 使用 end參數用指定的字元替換末尾的換行符

print(a,end='@') # 輸出:[email protected]

# 使用format

print('a={}'.format(a))# 輸出:a=1

print('a={0},b={1},c{2}'.format(a,b,c))# 輸出:a=1,b=2,c3

輸入input()

input輸入的始終是字元串,需要轉換為其他資料類型使用

python 資料類型

六個标準資料類型

Number(數字)

String(字元串)

List(清單)

Tuple(元組)

Sets(集合)

Dictionary(字典)

Number

包括:int(整型)、float(浮點型)、bool(布爾型)、complex(複數)、long(長整型)

清楚哪些值轉換為布爾類型後值是False

print(bool([])) # 輸出:False

print(bool('')) # 輸出:False

print(bool({})) # 輸出:False

print(bool(())) # 輸出:False

# 注意下面兩個的差別

print(bool(0)) # 輸出:False

print(bool('0')) # 輸出:True

浮點數的内置函數運算會有誤差,也就是小數的精度問題

String

字元串屬于序列,除此之外還有:元組、清單(集合和字典不是序列類型)

單引号和雙引号可以互換,也可以互嵌

三引号表示多行字元串(也可以作為文檔注釋)

另外:三引号内可以直接使用回車、制表符,可以不使用轉移字元來表示

字元串常用操作

連接配接和重複

print(‘hello’*3,’ wor’+’ld’) # 輸出:hellohellohello world

字元串的切片(左閉右開)

word = 'hello world'

print(word[0:5]) # 輸出:hello

print(word[:5]) # 輸出:hello

print(word[1:]) # 輸出:ello world

print(word[:]) # 輸出:hello world

print(word[0:5:2]) # 輸出:hlo

print(word[2:-2]) # 輸出:llo wor

print(word[-2:2]) # 輸出空串

轉義字元

要注意這種複雜的轉義字元一起輸出

在字元串内的“\r”、”\t”、”\n”等字元,會轉換為空白字元(回車符、水準制表符、換行符……)

printf('hello\tworld') # 輸出:hello world

Raw字元串(字元串内不轉義)

字元串字首為’R’或‘r’

print(r‘hello\tworld’) # 輸出:hello\tworld

變量及其指派

簡單指派

a = 1

多目标指派

a=b=c=1 # 這種情況下a、b、c都是引用同一個變量

這樣會報錯

a=(b=c=1) a=(b=1)

序列指派

左邊是元組、清單表示的多個變量,右側是元組、清單或字元串等序清單示的值。

序列元素個數必須和變量個數相等,否則會出錯

在變量名前使用“*”建立清單對象引用

a,b = 1,2 # 省略括号的元組指派

(c,d) = (2,3) # 元組指派

[e,f] = [4,’5’] # 清單指派

(g,h) = [‘6’,7] # 元組和清單可以交叉指派

(x,y,z) = ‘abc’ # 字元串指派,x=‘a’,y=‘b’,z=‘c’

(i,j) = (8,9,10) # 這是錯誤的,變量和值的個數必須相等

在變量名前使用“*”建立清單對象引用

x,*y = ‘abcd’

print(x,y) # 輸出:a [‘b’,’c’,’d’]

運算符和表達式

包括:算術運算符、關系運算符、字元串運算符、邏輯運算符。

算術運算符和表達式

算術運算符包括:加(+)、減(-)、乘(*)、除(/)、取餘(%)、整除(//)、幂運算(**)

a+=1和a=a+1等價,a-=1、a//=2等也類似

要注意這種複雜的表達式的運算優先級

int(8 * math.sqrt(36) * 10 ** (-2) *10 + 0.5)/10

運算順序如下:

int(8 * 6 * 10 ** (-2) * 10 + 0.5)/10

10**(2)=0.01

8 * 6 = 48

int(48 * 0.01 * 10 + 0.5 )/10

int(5.3)/10

5/10

0.5

邏輯運算符

and(邏輯與),or(邏輯或),not(邏輯非)

關系運算符

==(等于)、!=(不等于)、<>(不等于)、>(大于)、=(大于等于)、<=(小于等于)

運算符的優先級

最高優先級的三個運算符(優先級由高到低):** 幂運算、~ 安位取反、- 負号

最低優先級的幾個運算符(優先級由高到低):| 按位或、< > <= >= == != 關系運算符、not and or邏輯運算符

字元串運算符

下面這些運算對于清單、元組都有效(因為它們同屬序列類型)

字元串連接配接(+)

print('a'+'b') # 輸出:ab

重複字元串(*)

print('a'*3) # 輸出:aaa

索引字元串( [] )

a='hello'; print(a[1]); # 輸出:e

截取字元串( [:] )

print(a[1:4]) # 輸出:ell

成員運算符( in )

print('e' in a) # 輸出:True

成員運算符( not in )

print('e' not in a) # 輸出:False

Raw字元串( r/R )

print(R'he\tllo') # 輸出:hello\nllo

格式字元串(%)

print('hello %s%s' %('wor','ld')) # 輸出:hello world

格式化

%c(轉換為字元)

print('%c' %('hello')) # 報錯,必須是ASCII碼值或者一個字元,否則會出錯

%r(使用repr()進行字元串轉換)

print('%r' %('hello')) # 輸出:'hello'

%s(使用str()進行字元串轉換)

print('%s' %('hello')) # 輸出:hello

.format() 格式化

print('a={}'.format('a')) # 輸出:a=a

repr()函數和str()函數的差別就在于接受值和傳回值不同

repr()函數和str()函數,分别會調用輸入對象的__repr__()、__str__()特殊方法

%d或%i(轉換為有符号十進制數)

print(‘%d’ %(-10)) # 輸出:-10

%u(轉換為無符号十進制數)

print('%u' %(-10)) # 輸出:-10

有無符号是指在二進制下,最高位用來表示實際的數或是單純表示正負

%o(轉換為無符号八進制數)

print('%o' %(100)) # 輸出:144

%x或%X(轉換為無符号十六進制數)

print('%x' %(100)) # 輸出:64

%e或%E(轉換成科學計數法)

print('%e' %(1000)) # 輸出:1.000000e+03

%f或%F

print('%f' %(100) # 輸出:100.000000)

格式化操作輔助符

print('開始%10.2f結束' %(7.2222)) # 輸出:開始 7.22

%10.2f 表示:最小總長度為10,不足用前導空格補齊,長度大于等于10則正常顯示(這裡的長度不包括小數點)

位運算符

異或:二進制數逐位對比相同為0,不同為1

10^2==8 1010 異或 0010 結果為:1000

運算符

說明

&

按位與

|

按位或

^

按位異或

~

按位去反

<<

按位左移

>>

按位右移

python 常用函數

資料類型轉換函數

重點掌握加粗的函數

函數名

說明

int(str)

将字元串str轉換為整數

long(str)

将字元串str轉換為長整型整數

float(str)

将字元串str轉換為浮點數

eval(str)

将字元串str轉換為有效表達式并傳回表達式計算後的對象

str(x)

将數值x轉換為字元串

repr(obj)

将對象obj轉換為一個字元串

chr(x)

将整數x轉換為對應的ASCII字元

ord(x)

将字元x轉換為對應的ASCII碼

hex(x)

将一個整數x轉換為一個十六進制字元串

oct(x)

将一個整數x轉換為一個八進制字元串

tuple(squ)

将一個序列squ轉換為一個元組

list(squ)

将一個序列squ轉換為清單

set(squ)

将一個序列squ轉換為可變集合

dict(squ)

建立一個字典,squ是一個序列(key,value)元組

len(obj)

傳回對象的長度(字元個數、清單元素個數、字典key個數)

數學函數

函數名

說明

abs(x)

傳回數值x的絕對值

exp(x)

傳回e的x次幂

fabs(x)

傳回數字的絕對值

log10(x)

傳回以10為底的x的對數

pow(x,y)

傳回x的y次幂

floor(x)

x向下取整(小于等于x)

ceil(x)

x向上取整(大于等于x)

fmod(x,y)

求x/y的餘數

sin(x) cos(x)...

傳回x的三角函數值

python資料結構

python常用三種資料結構:序列、映射、集合

清單和元組有什麼相同點和不同點?(後面會給出解釋)

字元串

字元串是不可變的序列,不可以通過 str[n] = chr來改變字元串

字元串的切片(左閉右開)

word = 'hello world'

print(word[0:5]) # 輸出:hello

print(word[:5]) # 輸出:hello

print(word[1:]) # 輸出:ello world

print(word[:]) # 輸出:hello world

print(word[0:5:2]) # 輸出:hlo

print(word[2:-2]) # 輸出:llo wor

print(word[-2:2]) # 輸出空串

字元串轉清單

可以通過list()函數直接将字元串中的每個字元轉換為一個清單元素,也可以通過split()方法根據指定的分割符分割元素(預設以空格分割)。

word = 'hello world'

print(list(word)) # 輸出:['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

print(word.split()) # 輸出:['hello', 'world']

清單轉字元串

可以通過''.join()方法将字元串清單連接配接起來形成一個新的字元串

word = ['h','e','l','l','o']

words = ''.join(word)

print(words) # 輸出:hello

字元串查找

可以通過in關鍵字查找也可以通過字元串的find()方法,in關鍵字傳回True或False,find()方法傳回查找字元串的開始下标或-1,通過index()方法查找當沒有查找到時會報錯。

word = 'hello world'

print('llo' in word) # 輸出:True

print(word.find('llo')) # 輸出:2

print('ok' in word) # 輸出:False

print(word.find('0k')) # 輸出:-1

print(word.index('ok')) # 報錯

#帶開始和結束範圍的查找

print(word.find('llo',5,-1)) # 輸出:-1

print(word.index('llo',0,5)) # 輸出:2

字元串替換

replace()方法替換指定的字元串

str1 = 'hello world'

print(str1.replace('world','yznu')) # 輸出:hello yznu

# 指定參數來限制替換的次數,不指定參數預設替換所有比對的字元串

# 可以看到下面的語句隻替換了一個l

print(str1.replace('l',' yes',1)) # 輸出:he yeslo world

清單

清單的表示方法

[1,2,3,4]

建立清單

建立空清單、清單生成式、元組和字元串轉清單

# 建立一個空清單

lst = []

# 直接将清單指派給變量

lst = ['h','e','l','l','o']

# 元組轉清單

lst = list((1,2,3,4))

print(lst) # 輸出: [1,2,3,4]

# 字元串轉清單

lst = list('hello')

print(lst) # 輸出:['h','e','l','l','o']

# 字元串分割成清單

lst = 'hello world'.split()

print(lst) # 輸出:['hello', 'world']

# range()生成清單

lst = list(range(1, 6))

print(lst) # 輸出: [1,2,3,4,5]

# 清單生成式

lst = [x**2 for x in range(1,6)]

print(lst) # 輸出: [1,4,9,16,25]

# 複雜清單生成式子

lst = [x for x in lst if x>1 and x<25]

print(lst) # 輸出: [4,9,16]

清單元素删除

del(),pop(),remove()

# del 語句删除

lst = [1,2,3,4,5,6]

del(lst[5])

print(lst) # 輸出: [1,2,3,4,5]

# pop 方法删除并傳回指定下标的元素

print(lst.pop(4)) # 輸出: 5

print(lst) # 輸出: [1,2,3,4]

# remove 方法删除清單中的首次出現的某個值

lst.remove(4)

print(lst) # 輸出: [1,2,3]

清單分片

使用[:]對清單分片和對字元串分片相同,清單還能分片指派

# 清單分片指派

lst = [1,2,3,4,5]

lst[1:4] = [0,0,0] # 切片個數和指派個數一樣,否則報錯

print(lst) # 輸出: [1,0,0,0,5]

字元串轉清單和清單轉字元串

在上面字元串那一節已經寫過,不再贅述,回到那裡去看即可

清單常用的函數和方法

append(),count(),extend(),index(),sort(),len()

注意差別extend()和append()的用法

注意差別sort()和sorted()的用法

count()是非遞歸的統計一個元素出現的次數,也就是不會深入第二層

函數和方法

說 明

.append()

末尾追加一個元素(與.extend有何不同?)

.count()

統計某元素出現的次數(非遞歸式)

.extend()

以另一個序列的元素值去擴充原清單

.insert()

在指定下标處插入一個元素

.pop()

删除指定下标的元素并傳回該元素

.reverse()

翻轉清單

.sort()

對清單進行排序(與sorted函數有何不同?)

.index()

找到指定值第一次出現的下标(找不到報錯)

.remove()

移除在清單中第一次出現的指定的值

len()

傳回清單的元素個數

max()

傳回最大值

min()

傳回最小值

lst = [1,3,4,5]

# append 向清單中添加一個元素

lst.append([6,7])

print(lst) # 輸出:[1, 3, 4, 5, [6, 7]]

# extend 用序列擴充清單

lst.extend([8,9,10])

print(lst) # 輸出:[1, 3, 4, 5, [6, 7], 8, 9, 10]

# insert 方法在指定下标處插入一個值

lst.insert(1,2)

print(lst) # 輸出:[1, 2, 3, 4, 5, [6, 7], 8, 9, 10]

# count 統計一個元素在清單中出現的次數

lst = [1,[2,3],2,3]

print(lst.count(2)) # 輸出: 1

元組

元組的元素定義後不能修改

元組的表示方法

(1,2,3,4)

元組的建立

建立空元組、清單和字元串轉元組

元組不能直接使用清單的方法排序(因為不可修改)

# 建立一個空元組

tup = ()

# 直接将元組指派給變量

tup = (1,2,3)

# 清單轉元組

tup = tuple([1,2,3]) # 輸出:(1, 2, 3)

print(tup)

# 字元串轉元組

tup = tuple('hello')

print(tup) # 輸出:('h', 'e', 'l', 'l', 'o')

元組和清單的相同點和不同點

相同點

元組和清單都屬于序列

元組和清單都支援相同操作符,包括 +(連接配接)、*(重複)、[]索引、[:]切片、in、not in等

不同點

元組是不可變的對象

對清單進行的修改元素的操作,在元組上不可以(列如del删除一個元組中的元素會出錯,隻能将整個元組删掉,不能隻删某個元素)

字典

字典是映射類型

字典的key值必須是可哈希的(也可以說是不可修改的)

字典的表示方法

{key:value,key:value} {'name':'allen','age':18}

建立字典

建立空字典(使用空大括号預設建立字典,集合使用set())

fromkeys()建立字典、dict()建立字典

# 建立一個空字典

dict1 = {}

# 直接将字典指派給變量

dict1 = {'one': 1, 'two': 2, 'three': 3}

print(dict1) # 輸出:{'one': 1, 'two': 2, 'three': 3}

# dict建立字典(對比下面幾種建立字典的形式吧)

#方式1

dict1 = dict(one=1, two=2, three=3) #這樣建立字典,key不加引号

print(dict1) # 輸出:{'one': 1, 'two': 2, 'three': 3}

#方式2

temp = [('two',2), ('one',1), ('three',3)]

dict1 = dict(temp)

print(dict1) # 輸出:{'two': 2, 'one': 1, 'three': 3}

#方式3

temp = [['two',2], ['one',1], ['three',3]]

dict1 = dict(temp)

print(dict1)# 輸出:{'two': 2, 'one': 1, 'three': 3}

#方式4

temp = (['two',2], ['one',1], ['three',3])

dict1 = dict(temp)

print(dict1)# 輸出:{'two': 2, 'one': 1, 'three': 3}

# 使用fromkeys建立字典

subject = ['Python', '作業系統', '計算機網絡']

scores = dict.fromkeys(subject, 99)

print(scores) # 輸出:{'Python': 99, '作業系統': 99, '計算機網絡': 99}

字典常用函數和方法

dict(),values(),keys(),get(),clear(),pop(),in(),update(),copy()

注意差別get()和直接通路字典元素的差別

scores = {'Python': 99, '作業系統': 99, '計算機網絡': 99}

#print(socores['大學英語']) # 這會報錯,因為不存在'大學英語'這個鍵

print(scores.get('大學英語')) # 輸出:None

# values傳回字典的所有值

print(scores.values()) # 輸出:dict_values([99, 99, 99])

# keys傳回字典的所有鍵

print(scores.keys()) # 輸出:dict_keys(['Python', '作業系統', '計算機網絡'])

# items傳回字典的所有鍵和值

print(scores.items()) # 輸出:dict_items([('Python', 99), ('作業系統', 99), ('計算機網絡', 99)])

# 使用keys周遊

for k in scores.keys():

print(k,end=' ');

# 輸出: Python 作業系統 計算機網絡

# 使用values周遊

for v in scores.values():

print(v,end=' ');

# 輸出:99 99 99

# 使用items周遊

for k,v in scores.items():

print(k,v,end=';');

# 輸出:Python 99;作業系統 99;計算機網絡 99;

# in查詢一個字典中是否包含指定鍵

print( 'Python' in scores) # 輸出:True

print( '資料結構' in scores) # 輸出:False

# update更新字典,如果包含相同的鍵将會覆寫原來的對應的那個鍵值

dict1 = {'國文':90,'數學':91}

scores.update(dict1)

print(scores) # 輸出:{'Python': 99, '作業系統': 99, '計算機網絡': 99, '國文': 90, '數學': 91}

# 删除字典元素

del(scores['國文'])

print(scores) # 輸出:{'Python': 99, '作業系統': 99, '計算機網絡': 99, '數學': 91}

scores.pop('數學')

print(scores) # 輸出:{'Python': 99, '作業系統': 99, '計算機網絡': 99}

# 清空字典

scores.clear()

print(scores) # 輸出:{}

集合

集合的元素不會有重複,利用這個特性程式設計題中可以去重

集合内的元素隻能是可哈希的資料類型(也可以說是不可修改的),無法存儲清單、字典、集合這些可變的資料類型

集合是無序的,是以每次輸出時元素的排序順序可能都不相同

建立集合

建立空集合不能直接用大括号,大括号預設建立空字典

将序列轉為集合

# 建立一個空集合不能直接用大括号

set1 = set()

# 将集合直接指派給變量

set1 = {'Python','計算機網絡','作業系統'}

print(set1) # 輸出:{'作業系統', '計算機網絡', 'Python'}

# 清單轉集合

set1 = set(['作業系統', '計算機網絡', 'Python','作業系統'])

print(set1) # 輸出:{'Python', '計算機網絡', '作業系統'}

# 字元串轉集合

set1 = set('作業系統')

print(set1) # 輸出:{'系', '作', '操', '統'}

集合的一些操作

set1 = {'Python','計算機網絡','作業系統'}

set2 = set(['國文','作業系統','計算機網絡'])

# 集合中沒有 + 的操作

# print(set1+set2) #這樣會出錯

# 差集(set1有但是set沒有的元素)

print(set1 - set2) # 輸出:{'Python'}

# 交集(set1和set2都有的元素)

print(set1 & set2) # 輸出:{'作業系統','計算機網絡'}

# 并集(set1和set2所有的元素)

print(set1 & set2) # 輸出:{'國文', '作業系統', '計算機網絡', 'Python'}

# 不同時包含于a和b的元素

print(set1 ^ set2)

集合的常用方法

set(),add(),update(),remove()

集合不支援用 del() 删除一個元素

set1 = set(['作業系統', '計算機網絡', 'Python','作業系統'])

# add 向集合中添加一個元素

set1.add('國文')

print(set1) # 輸出:{'國文', '計算機網絡', '作業系統', 'Python'}

# remove 删除集合中一個元素

set1.remove('國文')

print(set1) # 輸出:{'Python', '作業系統', '計算機網絡'}

程式流程控制(記得語句後面的冒号:)

程式流程控制一定要注意語句後面的冒号和語句塊之間的縮進

分支選擇

單分支

if:

多分支

if:

……

elif:

……

else:

……

程式例子

# 判斷一個人的身材是否正常

height = float(input("輸入身高(米):"))

weight = float(input("輸入體重(千克):"))

bmi = weight / (height * height) #計算BMI指數

if bmi<18.5:

print("BMI指數為:"+str(bmi))

print("體重過輕")

elif bmi>=18.5 and bmi<24.9:

print("BMI指數為:"+str(bmi))

print("正常範圍,注意保持")

elif bmi>=24.9 and bmi<29.9:

print("BMI指數為:"+str(bmi))

print("體重過重")

else:

print("BMI指數為:"+str(bmi))

print("肥胖")

#輸入身高(米):1.7

#輸入體重(千克):55

#BMI指數為:19.031141868512112

#正常範圍,注意保持

三目運算

max = a if a>b else b if為真max=a,否則max=b

a = int(input('請輸入a:')) # 假設輸入10

b = int(input('請輸入b:')) # 假設輸入15

if a>b:

max = a

else:

max = b

print(max) # 輸出:15

max = a if a>b else b

print(max) # 輸出:15

循環結構

while循環

while循環的格式

# 循環的初始化條件

num = 1

# 當 num 小于100時,會一直執行循環體

while num <= 100 :

print("num=", num)

# 疊代語句

num += 1

print("循環結束!")

for循環

for循環的格式

for循環周遊字典、集合、清單、字元串、元組

subjects = ['Python','作業系統','網絡']

# 循環周遊清單1

for i in subjects:

print(i,end=' ') # 輸出:Python 作業系統 網絡

print(' ')

# 循環周遊清單2

for i in range(len(subjects)):

print(subjects[i],end=' ') # 輸出:Python 作業系統 網絡

print(' ')

# 周遊字元串,元組也類似,就不寫了

# 循環周遊清單1 這種形式也可以用于 字典、集合,但 循環周遊清單2這種形式不行

# 集合不能使用索引(因為它是無序的),是以使用set[i]這種形式輸出會報錯

# 字典必須用鍵去索引值,dict[key]這種形式

清單生成式

range()函數與for循環的使用

range函數的格式如下:

range(start, end, step)

start:計數從 start 開始。預設是從0開始。例如 range(5)等價于range(0, 5)

end:計數到end結束,但不包括 end 例如:range(0, 5) 是 0, 1, 2, 3, 4 沒有5

step:步長,預設為1。例如:range(0, 5) 等價于 range(0, 5, 1)

# 清單生成式

lst = [x for x in range(2,11,2)]

print(lst) # 輸出:[2, 4, 6, 8, 10]

lst = [x*2 for x in range(2,11,2)]

print(lst) # 輸出:[4, 8, 12, 16, 20]

# 直接循環range函數

for i in range(2,11,2):

print(i,end=' ') # 輸出:2 4 6 8 10

print(' ')

for i in range(11):

print(i,end=' ') # 輸出:0 1 2 3 4 5 6 7 8 9 10

print(' ')

break 和 continue 關鍵字

# 輸出1-50之間的偶數

# 循環的初始化條件

num = 1

while num <= 100 :

if(num > 50): # 當num>50跳出循環

break

if(num%2 != 0 ): # num為奇數跳過輸出,直接加一進入下一次循環

num += 1

continue

print("num=", num)

# 疊代語句

num += 1

print("循環結束!")

Python函數和子產品

函數

函數的定義

def 函數名():

函數體

return語句

return語句可以沒有

函數的嵌套定義,python函數内是可以定義函數的

函數的參數

預設參數

預設參數應該放在必須參數後面,類似這樣 def(a,b,c=1):

可變參數

形參定義形式為*second,second會在函數中被解析為一個元組

# 可變參數1

def print_str(first, *second):# first必須要指定一個參數,second可以指定0個或多個參數

print(first,end=' ')

print(second)

print_str('hello') # 輸出:hello ()

print_str('hello','world') # 輸出:hello ('world',)

print_str('hello','world','yznu') #輸出: hello ('world', 'yznu')

形參定義形式為 **anything,anything會被解析為一個字典

# 可變參數2

def printStr(**anything):

print(anything)

printStr(Python = 99, 作業系統 = 99) # 輸出:{'Python': 99, '作業系統': 99}

變量的作用範圍

局部變量和全局變量的定義

函數外不能通路函數内的變量

全局變量和局部變量同名,預設通路局部變量

在函數内要想改變函數外的變量需要用global關鍵字

# 函數外部不能通路函數内的變量(局部變量)

def demo(name):

str1 = 'hello'# 局部變量

print(str1,name)

demo('sir') # 輸出:hello sir

# print(str1) # 通路函數内的局部變量會出錯

# print(name) # 通路函數内的局部變量會出錯

# 全局變量和局部變量同名,預設通路局部變量

str1 = 'hi' # 全局變量

def demo(name):

str1 = 'hello' # 局部變量

print(str1,name)

demo('sir') # 輸出:hello sir

print(st1) # 輸出:hi

# 在函數内要想改變函數外的變量需要用 global 關鍵字

str1 = 'hi' # 全局變量

def demo(name):

global str1 # 下面,對str1的修改會影響到函數外部的全局變量 str1

str1 = 'hello' # 局部變量

print(str1,name)

demo('sir') # 輸出:hello sir

print(st1) # 輸出:hello

python子產品

Python 子產品就是一個 Python 檔案,以 .py 結尾,包含了 Python 對象定義和Python語句。

python子產品的幾種導入方法

import 子產品1,子產品2 (導入一個或多個子產品)

from 子產品 import 函數或類 (導入子產品内的部分函數或類)

from 子產品 import * (導入子產品下的所有東西)

Python面向對象

面向對象基礎

面向對象的三個特性

封裝性

繼承性

多态性

類的定義

class Demo:

'''随便定義了一個類'''

# 下面定義了一個類屬性

add = 'hello'

# 下面定義了一個執行個體方法

def say(self, content):

print(content)

文檔字元串可以省略,類體中可以定義屬性、方法

屬性

類屬性和執行個體屬性的差別?

類屬性為所有執行個體共享,可以通過類名調用和修改類變量。

執行個體屬性為每個執行個體所獨有,隻能通過執行個體調用和修改。

私有屬性

不能在類外部直接通過執行個體調用私有屬性,可以通過執行個體方法調用和修改

以雙下劃線開頭,但不以雙下劃線結尾的屬性為私有屬性

class Demo:

def __init__(self, word):

self.__word = word # __word就是一個私有屬性

def print_str(self):

print(self.__word)

a = Demo('hello') # 建立了一個執行個體,将執行個體指派給a

方法

在類外部不能調用私有方法

幾種方法的定義、作用和差別

self和cls參數的用法

__init__()方法的使用

@classmethod 的使用

@staticmethod 的使用

__init()__和__new()__有什麼差別?

__init__() 方法在初始化一個執行個體的時候調用。

__new__()方法是建立執行個體的時候調用。

建立執行個體在初始化之前

# __init__() 和 __new__()的示例

class Person(object):

def __init__(self, name):

print('執行個體初始化了',end=' ')

self.name = name

def __new__(cls, name):

print('執行個體建立了',end=' ')

return object.__new__(cls)

person = Person('Sir')

print(person.name)

#輸出如下(輸出沒有三引号)

"""

執行個體建立了

執行個體初始化了

Sir

"""

執行個體方法

執行個體方法必須通過生成的執行個體調用

類方法

類下的執行個體對象都可以調用類方法

類方法可以使用類名直接調用,也可以使用執行個體對象來調用

靜态方法

靜态方法通過類直接調用,不需要建立對象,不會隐式傳遞self

類的繼承

單繼承

# 這就是一個簡單的單繼承示例,C繼承A

class A(object):

def work(self):

print('A.work')

class C(A): # C繼承了A

def work(self):

print('C.work')

多繼承

在多繼承下,調用一個方法,清楚該方法的繼承走向,也就是重名時優先調用哪一個次之又調用哪個

# 多繼承1

class A(object):

def work(self):

print('A.work')

class B(object):

def work(self):

print('B.work')

class C(A): # C繼承了A

def work(self):

print('C.work')

class D(B): # D繼承了B

def work(self):

print('D.work')

class E(D,C): # E繼承了D和C

def work(self):

print('E.work')

e = E()

e.work() # 輸出 E.work

# 多繼承2

class A(object):

def work(self):

print('A.work')

class B(object):

def work(self):

print('B.work')

class C(A): # C繼承了A

def work(self):

print('C.work')

class D(B): # D繼承了B

def work(self):

print('D.work')

class E(D,C): # E繼承了D和C,自身沒有work方法

pass

e = E()

e.work() # 輸出 D.work

# 多繼承3

class A(object):

def work(self):

print('A.work')

class B(object):

def work(self):

print('B.work')

class C(A): # C繼承了A

def work(self):

print('C.work')

class D(B): # D繼承了B,自身沒有work方法

pass

class E(D,C): # E繼承了D和C,自身沒有work方法

pass

e = E()

e.work() # 輸出 B.work

# 多繼承4

class A(object):

def work(self):

print('A.work')

class B(object):

pass

class C(A): # C繼承了A

def work(self):

print('C.work')

class D(B): # D繼承了B,自身沒有work方法

pass

class E(D,C): # E繼承了D和C,自身沒有work方法

pass

e = E()

e.work() # 輸出 C.work

# 多繼承5

class A(object):

def work(self):

print('A.work')

class B(object):

pass

class C(A): # C繼承了A,自身沒有work方法

pass

class D(B): # D繼承了B,自身沒有work方法

pass

class E(D,C): # E繼承了D和C,自身沒有work方法

pass

e = E()

e.work() # 輸出 A.work

E繼承了D和C,D繼承了B,C繼承了A

上面程式的繼承走向: E -> D -> B -> C -> A

也就是會先在E中找同名的方法,找到了就結束

如果沒有找到再到D中找,找到了結束

類似,再到B中找,再到C中找,再到A中找

下面還有一個多繼承的例子

E繼承了D和C,D繼承了A,C繼承了A

繼承走向: E -> D -> C -> A

需要掌握的一些操作

這道程式設計題需要掌握

給定一個字元串從中随機抽取一些字元組成新的字元串,要求組成的字元串中不能有重複字元,生成的字元串不能重複,一共可以生成多少個字元串。

我就不貼出我的代碼來了,我怕我自己做的是錯的

随機抽取

random.sample()

從一個序列中随機抽出指定數量的元素,并以清單形式傳回

import random

str1 = 'abcde'

lst = [1,2,3,4,5]

tuple1 = (1,2,3,4,5)

# 随機從字元串中抽取5個字元組成新的清單

rand_str = random.sample(str1, 5)

print(rand_str)

# 随機從清單中抽取5個元素組成新的清單

rand_lst = random.sample(lst,5)

print(rand_lst)

# 随機從元組中抽取5個元素組成新的清單

rand_tuple = random.sample(tuple1,5)

print(rand_tuple)

random.choice()

從一個序列中随機抽取一個元素

import random

str1 = 'abcde'

lst = [1,2,3,4,5]

tuple1 = (1,2,3,4,5)

# 從字元串中随機抽取一個字元

a = random.choice(str1)

print(a)

# 從元組中随機抽取一個元素

a = random.choice(tuple1)

print(a)

去重

利用集合去重

set1 = set()

set1.add(1)

set1.add(2)

set1.add(3)

set1.add(1)

set1.add(2)

set1.add(3)

print(set1) # 輸出:{1, 2, 3}

利用循環周遊清單去重

list1 = [2, 1, 3, 6, 2, 1]

temp = []

for i in list1:

if not i in temp:

temp.append(i)

print(temp) # 輸出:[2, 1, 3, 6]

一些特殊的字元串判斷操作

str1 = 'hello'

str2 = '1234'

str3 = 'hello1234'

str4 = '\n \t'

# 判斷所有字元都是字母

print(str1.isalpha()) # 輸出:True

# 判斷所有字元都是數字

print(str2.isdigit()) # 輸出:True

# 判讀所有字元都是 數字或者字母

print(str3.isalnum()) # 輸出:True

# 判斷所有字元都是空白字元(不隻是空格)

print(str4.isspace()) # 輸出:True

字元串轉位元組

str1 = 'yznu'

print(str1) # 輸出:yznu

# 下面的輸出都是位元組類型

# 第一種

print(b'yznu') # 輸出:b'yznu'

# 第二種

str2 = bytes(str1, encoding='utf-8')

print(str2) # 輸出:b'yznu'

# 第三種 注意:encode方法并不會将原來的字元串變為位元組,而是重新複制一份位元組

str2 = str1.encode('utf-8')

print(str2) # 輸出:b'yznu'

位元組轉字元串

byte = b'yznu' # 這是位元組

# 第一種

str1 = str(byte, encoding="utf-8")

print(str1) # 輸出:yznu

# 第二種

str1 = bytes.decode(byte)

print(str1) # 輸出:yznu

應該複習得差不多了吧,祝各位考試順利!

新年快樂![]( ̄▽ ̄)*