1. 程式人生 > 實用技巧 >python基礎入門這一篇就夠

python基礎入門這一篇就夠

Python 是一種通用程式語言,其在科學計算和機器學習領域具有廣泛的應用。

1 量、運算子與資料型別

1.1 註釋

1.2 運算子

1.3 變數和賦值

1.4 資料型別與轉換

1.5 print() 函式

2 條件語句

2.1 if 語句

2.2 if - else 語句

2.3 if - elif - else 語句

2.4 assert 關鍵詞

3 迴圈語句

3.1 while 迴圈

3.2 while - else 迴圈

3.3 for 迴圈

3.4 for - else 迴圈

3.5 range() 函式

3.6 enumerate()函式

3.7 break 語句

3.8 continue 語句

3.9 pass 語句

3.10 推導式

4 異常處理

4.1 Python 標準異常總結

4.2 Python標準警告總結

4.3 try - except 語句

4.6 raise語句

1.量、運算子與資料型別

註釋

1. 在 Python 中, # 表示註釋,作用於整行。

【例子】單行註釋

# 這是一個註釋
print("Hello world")#Helloworld

1. ''' ''' 或者 """ """ 表示區間註釋,在三引號之間的所有內容被註釋

【例子】

多行註釋

'''這是多行註釋,用三個單引號這是多行註釋,用三個單引號這是多行註釋,用三個單引號 '''

print("Hello china")
# Hello china

"""這是多行註釋,用三個雙引號這是多行註釋,用三個雙引號這是多行註釋,用三個雙引號'''

print("hello china")

#hellochina

1.2運算子

算術運算子

操作符 名稱     示例

+ 加 [1 + 1]

- 減 [2 - 1]

*乘 [3*4]

/ 除 [3 / 4]

// 整除 [(地板除) 3 // 4]

%取餘[3%4]

** 次方 [2 ** 3]

【例子】

print(1 + 1) # 2

print(2 - 1) # 1

print(3 * 4) # 12

print(3 / 4) # 0.75

print(3 // 4) # 0

print(3 % 4) # 3

print(2 ** 3) # 8

比較運算子

操作符  名稱        示例

> 大於 [2 > 1]

>= 大於等於 [2 >= 4]

< 小於 [1 < 2]

<=小於等於[5<=2]

==等於 [3==4]

!= 不等於 [3 != 5]

【例子】

print(2 > 1) # True

print(2 >= 4) # False

print(1 < 2) # True

print(5 <= 2) # False

print(3 == 4) # False

print(3 != 5) # True

邏輯運算子

操作符   名稱    示例

and 與 (3 > 2) and (3 < 5)

or 或 (1 > 3) or (9 < 2)

not 非 not (2 > 1)

【例子】

print((3 > 2) and (3 < 5)) # True

print((1 > 3) or (9 < 2)) # False

print(not (2 > 1)) # False

位運算子

操作符    名稱        示例

~ 按位取反 ~4

& 按位與 4 & 5

| 按位或 4 | 5

^ 按位異或 4 ^ 5

<< 左移 4 << 2

>> 右移 4 >> 2

【例子】

print(bin(4)) # 0b100

print(bin(5)) # 0b101

print(bin(~4), ~4) # -0b101 -5

print(bin(4 & 5), 4 & 5) # 0b100 4

print(bin(4 | 5), 4 | 5) # 0b101 5

print(bin(4 ^ 5), 4 ^ 5) # 0b1 1

print(bin(4 << 2), 4 << 2) # 0b10000 16

print(bin(4 >> 2), 4 >> 2) # 0b1 1

三元運算子

x, y = 4, 5
if x < y:
small = x
else:
small = yprint(small) # 4

【例子】

x, y = 4, 5

small = x if x < y else yprint(small) # 4

其他運算子

操作符     名稱         示例

in 存在 'A' in ['A', 'B', 'C']

not in 不存在 'h' not in ['A', 'B', 'C']

is 是 "hello" is "hello"

is not 不是 "hello" is not "hello"

【例子】

letters = ['A', 'B', 'C']
if 'A' in letters:
print('A' + ' exists')

if 'h' not in letters:

print('h' + ' not exists')

# A exists

# h not exists

【例子】比較的兩個變數均指向不可變型別。

a = "hello"

b = "hello"

print(a is b, a == b) # True
True
print(a is not b, a != b) # False False

【例子】比較的兩個變數均指向可變型別。

a = ["hello"]

b = ["hello"]

print(a is b, a == b) # False

True
print(a is not b, a != b) # True False

注意:1. is, is not 對比的是兩個變數的記憶體地址

2. ==, != 對比的是兩個變數的值

3. 比較的兩個變數,指向的都是地址不可變的型別(str等),那麼is,is not 和 ==,!= 是完全等價的。

4. 對比的兩個變數,指向的是地址可變的型別(list,dict,tuple等),則兩者是有區別的。

運算子的優先順序

1.一元運算子優於二元運算子。例如 3 ** -2 等價於 3 ** (-2) 。

2.先算術運算,後移位運算,最後位運算。例如 1 << 3 + 2 & 7 等價於 (1 << (3 + 2)) & 7 。

3. 邏輯運算最後結合。例如 3 < 4 and 4 < 5 等價於 (3 < 4) and (4 < 5) 。

【例子】

print(-3 ** 2) # -9

print(3 ** -2) # 0.1111111111111111

print(1 << 3 + 2 & 7) # 0

print(-3 * 2 + 5 / -2 - 4) # -12.5

print(3 < 4 and 4 < 5) # True

1.3 變數和賦值

1. 在使用變數之前,需要對其先賦值。

2. 變數名可以包括字母、數字、下劃線、但變數名不能以數字開頭。

3. Python 變數名是大小寫敏感的,foo != Foo。

【例子】

teacher="我的程式人生"

print(teacher)#我的程式人生

【例子】

first = 2

second = 3

third = first + secondprint(third) # 5

【例子】

myTeacher = "我的程式人生"


yourTeacher = "你的程式人生"

ourTeacher = myTeacher + ',' + yourTeacher
print(ourTeacher)
# 我的程式人生,你的程式人生

1.4 資料型別與轉換

型別     名稱        示例

int 整型 <class 'int'> -876, 10

float 浮點型 <class 'float'> 3.149, 11.11

bool 布林型 <class 'bool'> True, False

整型

【例子】通過 print() 可看出 a 的值,以及類 (class) 是 int 。

a = 1031

print(a, type(a))

# 1031 <class 'int'>

Python 裡面萬物皆物件(object),整型也不例外,只要是物件,就有相應的屬性 (attributes) 和方法 (methods)。

【例子】

b = dir(int)print(b)


# ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__',

# '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__',

# '__float__', '__floor__', '__floordiv__', '__format__', '__ge__',

# '__getattribute__', '__getnewargs__', '__gt__', '__hash__',

# '__index__', '__init__', '__init_subclass__', '__int__', '__invert__',

# '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__',
# '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__',

# '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__',

# '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__',
# '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__',

# '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__',

# '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__',

# 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag',# 'numerator', 'real', 'to_bytes']

對它們有個大概印象就可以了,具體怎麼用,需要哪些引數 (argument),還需要查文件。看個 bit_length() 的例子。

【例子】找到一個整數的二進位制表示,再返回其長度。

a = 1031print(bin(a))
# 0
b10000000111

print(a.bit_length()) # 11

浮點型

【例子】

print(1, type(1))

# 1 <class 'int'>

print(1., type(1.))

# 1.0 <class 'float'>

a = 0.00000023

b = 2.3e-7

print(a)

# 2.3e-07
print(b)
# 2.3e-07

有時候我們想保留浮點型的小數點後 n 位。可以用 decimal 包裡的 Decimal 物件和 getcontext() 方法來 實現。

import decimal

from decimal import Decimal

Python 裡面有很多用途廣泛的包 (package),用什麼你就引進 (import) 什麼。包也是物件,也可以用上面提到 的 dir(decimal) 來看其屬性和方法。

【例子】 getcontext() 顯示了 Decimal 物件的預設精度值是 28 位 ( prec=28 )。

a = decimal.getcontext()

print(a)
# Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,

# capitals=1, clamp=0, flags=[],

# traps=[InvalidOperation, DivisionByZero, Overflow])
b = Decimal(1) / Decimal(3)

print(b)

# 0.3333333333333333333333333333

【例子】使 1/3 保留 4 位,用 getcontext().prec 來調整精度。

decimal.getcontext().
prec = 4
c = Decimal(1) / Decimal(3)

print(c)# 0.3333

布林型

布林 (boolean) 型變數只能取兩個值, True 和 False 。當把布林型變數用在數字運算中,用 1 和 0 代表 True 和 False 。

【例子】

print(True + True) # 2

print(True + False) # 1

print(True * False) # 0

除了直接給變數賦值 True 和 False ,還可以用 bool(X) 來建立變數,其中 X 可以是

1. 基本型別:整型、浮點型、布林型

2. 容器型別:字串、元組、列表、字典和集合

【例子】 bool 作用在基本型別變數:X 只要不是整型 0 、浮點型 0.0 , bool(X) 就是 True ,其餘就是 False 。

print(type(0), bool(0), bool(1))# <class 'int'> False True

print(type(10.31), bool(0.00), bool(10.31))# <class 'float'> False True

print(type(True), bool(False), bool(True))# <class 'bool'> False True

【例子】 bool 作用在容器型別變數:X 只要不是空的變數, bool(X) 就是 True ,其餘就是 False 。

print(type(''), bool(''), bool('python'))# <class 'str'> False True

print(type(()), bool(()), bool((10,)))# <class 'tuple'> False True

print(type([]), bool([]), bool([1, 2]))# <class 'list'> False True

print(type({}), bool({}), bool({'a': 1, 'b': 2}))# <class 'dict'> False True

print(type(set()), bool(set()), bool({1, 2}))# <class 'set'> False True

確定 bool(X) 的值是 True 還是 False ,就看 X 是不是空,空的話就是 False ,不空的話就是 True 。

1. 對於數值變數, 0 , 0.0 都可認為是空的。

2. 對於容器變數,裡面沒元素就是空的。

獲取型別資訊

1. type(object) 獲取型別資訊

【例子】

print(type(1)) # <class 'int'>

print(type(5.2)) # <class 'float'>

print(type(True)) # <class 'bool'>

print(type('5.2')) # <class 'str'>

1. isinstance(object, classinfo) 判斷一個物件是否是一個已知的型別。

【例子】

print(isinstance(1, int)) #True

print(isinstance(5.2, float)) #True

print(isinstance(True, bool)) #True

print(isinstance('5.2', str)) #True

注:

1. type() 不會認為子類是一種父類型別,不考慮繼承關係。

2. isinstance() 會認為子類是一種父類型別,考慮繼承關係。

如果要判斷兩個型別是否相同推薦使用 isinstance()

型別轉換

1. 轉換為整型 int(x, base=10)

2. 轉換為字串 str(object='')

3. 轉換為浮點型 float(x)

【例子】

print(int('520')) # 520

print(int(520.52)) # 520

print(float('520.52')) # 520.52

print(float(520)) # 520.0

print(str(10 + 10)) # 20

print(str(10.1 + 5.2)) # 15.3

1.5 print() 函式

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

1. 將物件以字串表示的方式格式化輸出到流檔案物件file裡。其中所有非關鍵字引數都按 str() 方式進行轉換 為字串輸出;

2. 關鍵字引數 sep 是實現分隔符,比如多個引數輸出時想要輸出中間的分隔字元;

3. 關鍵字引數 end 是輸出結束時的字元,預設是換行符 \n ;

4. 關鍵字引數 file 是定義流輸出的檔案,可以是標準的系統輸出 sys.stdout ,也可以重定義為別的檔案;

5. 關鍵字引數 flush 是立即把內容輸出到流檔案,不作快取。

【例子】沒有引數時,每次輸出後都會換行。

shoplist = ['apple', 'mango', 'carrot', 'banana'
]
print("This is printed without 'end'and 'sep'.")

for item in shoplist:

print(item)

# This is printed without 'end'and 'sep'.# apple# mango# carrot# banana

【例子】每次輸出結束都用 end 設定的引數 & 結尾,並沒有預設換行。

shoplist = ['apple', 'mango', 'carrot', 'banana']

print("This is printed with 'end='&''.")

for item in shoplist:

print(item, end='&')

print('hello world')# This is printed with 'end='&''
.
# apple&mango&carrot&banana&hello world

【例子】 item 值與 'another string' 兩個值之間用 sep 設定的引數 & 分割。由於 end 引數沒有設定,因此默 認是輸出解釋後換行,即 end 引數的預設值為 \n 。

2 條件語句

2.1 if 語句

if expression:

expr_true_suite

1. if 語句的 expr_true_suite 程式碼塊只有當條件表示式 expression 結果為真時才執行,否則將繼續執行緊 跟在該程式碼塊後面的語句。

2. 單個 if 語句中的 expression 條件表示式可以通過布林操作符 and , or 和 not 實現多重條件判斷。

【例子】

if 2 > 1and not 2 > 3:


print('Correct Judgement!')# Correct Judgement!

2.2 if - else 語句

if expression:

expr_true_suite
else:

expr_false_suite

1. Python 提供與 if 搭配使用的 else,如果 if 語句的條件表示式結果布林值為假,那麼程式將執行 else 語句後的 程式碼。

【例子】

temp = input("猜一猜小姐姐想的是哪個數字?")
guess = int(temp) # input 函式將接收的任何資料型別都預設為 str。
if guess == 666:
print("你太瞭解小姐姐的心思了!")
print("哼,猜對也沒有獎勵!")
else:

print("猜錯了,小姐姐現在心裡想的是666!")

print("遊戲結束,不玩兒啦!")

if 語句支援巢狀,即在一個 if 語句中嵌入另一個 if 語句,從而構成不同層次的選擇結構。

【例子】Python 使用縮排而不是大括號來標記程式碼塊邊界,因此要特別注意 else 的懸掛問題。

hi = 6if hi > 2:

if hi > 7:

print('好棒!好棒!')

else:

print('切~')# 無輸出

【例子】

temp = input("猜一猜小姐姐想的是哪個數字?")
guess = int(temp)if guess > 8:
print("大了,大了")
else:
if guess == 8:
print("你太瞭解小姐姐的心思了!")
print("哼,猜對也沒有獎勵!")
else:
print("小了,小了")print("遊戲結束,不玩兒啦!")

2.3 if - elif - else 語句

if expression1:
expr1_true_suite
elif expression2:
expr2_true_suite
elif expressionN:

exprN_true_suite

else:

expr_false_suite

1. elif 語句即為 else if,用來檢查多個表示式是否為真,並在為真時執行特定程式碼塊中的程式碼

【例子】

temp = input('請輸入成績:')

source = int(temp)

if 100 >= source >= 90:

print('A')elif 90 > source >= 80:

print('B')elif 80 > source >= 60:

print('C')elif 60 > source >= 0:

print('D')

else:

print('輸入錯誤!')

2.4 assert 關鍵詞

1. assert 這個關鍵詞我們稱之為“斷言”,當這個關鍵詞後邊的條件為 False 時,程式自動崩潰並拋 出 AssertionError 的異常。

【例子】

my_list = ['lsgogroup']

my_list.pop(0)

assert len(my_list) > 0

# AssertionError

【例子】在進行單元測試時,可以用來在程式中置入檢查點,只有條件為 True 才能讓程式正常工作。

assert 3 > 7#
AssertionError

3 迴圈語句

3.1 while 迴圈

while 語句最基本的形式包括一個位於頂部的布林表示式,一個或多個屬於 while 程式碼塊的縮排語句。

while 布林表示式:

程式碼塊

while 迴圈的程式碼塊會一直迴圈執行,直到布林表示式的值為布林假。

如果布林表示式不帶有 <、>、==、!=、in、not in 等運算子,僅僅給出數值之類的條件,也是可以的。

當 while 後寫入一個非零整數時,視為真值,執行迴圈體;寫入 0 時,視為假值,不執行迴圈體。也可以寫 入 str、list 或任何序列,長度非零則視為真值,執行迴圈體;否則視為假值,不執行迴圈體。

【例子】

count = 0while count < 3:
temp = input("猜一猜小姐姐想的是哪個數字?")
guess = int(temp) if guess > 8:
print("大了,大了")
else:
if guess == 8:
print("你太瞭解小姐姐的心思了!")
print("哼,猜對也沒有獎勵!")
count = 3
else:
print("小了,小了")
count = count + 1
print("遊戲結束,不玩兒啦!")

【例子】布林表示式返回0,迴圈終止。

string = 'abcd'while string:

print(string)

string=string[1:]# abcd# bcd# cd# d

3.2 while - else 迴圈

while 布林表示式:
程式碼塊
else:

程式碼塊

當 while 迴圈正常執行完的情況下,執行 else 輸出,如果 while 迴圈中執行了跳出迴圈的語句,比如 break ,將不執行 else 程式碼塊的內容。

【例子】

count = 0while count < 5:
print("%d is less than 5" % count)
count = count + 1
else:

print("%d is not less than 5" % count)

# 0 is less than 5# 1 is less than 5

# 2 is less than 5# 3 is less than 5

# 4 is less than 5# 5 is not less than 5

【例子】

count = 0while count < 5:    print("%d is less than 5" % count)
count = 6
break
else:

print("%d is not less than 5" % count)# 0 is less than 5

3.3 for 迴圈

for 迴圈是迭代迴圈,在Python中相當於一個通用的序列迭代器,可以遍歷任何有序序列,

如 str、list、tuple 等,也可以遍歷任何可迭代物件,如 dict 。

for 迭代變數 in 可迭代物件:

程式碼塊

每次迴圈,迭代變數被設定為可迭代物件的當前元素,提供給程式碼塊使用。

【例子】

for i in 'ILoveLSGO':

print(i,end='')#不換行輸出# I L o v e L S G O

【例子】

member = ['張三', '李四', '劉德華', '劉六', '周潤發']

for each in member:

print(each)# 張三# 李四# 劉德華# 劉六# 周潤發

for i in range(len(member)):

print(member[i])# 張三# 李四# 劉德華# 劉六# 周潤發

【例子】

dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

for key, value in dic.items():

print(key,value,sep=':',end='')# a:1 b:2 c:3 d:4

【例子】

dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

for key in dic.keys():

print(key,end='')# a b c d

【例子】

dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

for value in dic.values():

print(value,end='')# 1 2 3 4

3.4 for - else 迴圈

for 迭代變數 in 可迭代物件:

程式碼塊else: 程式碼塊

當 for 迴圈正常執行完的情況下,執行 else 輸出,如果 for 迴圈中執行了跳出迴圈的語句,比如 break ,將不 執行 else 程式碼塊的內容,與 while - else 語句一樣。

【例子】

for num in range(10, 20): # 迭代 10 到 20 之間的數字

for i in range(2, num): # 根據因子迭代

if num % i == 0: # 確定第一個因子

j = num / i # 計算第二個因子

print('%d 等於 %d * %d' % (num, i, j))

break # 跳出當前迴圈

else: # 迴圈的 else 部分

print(num, '是一個質數')# 10 等於 2 * 5# 11 是一個質數# 12 等於 2 * 6# 13 是一個質數# 14 等於 2 * 7# 15 等於 3 * 5# 16 等於 2 * 8# 17 是一個質數# 18 等於 2 * 9# 19 是一個質數

3.5 range() 函式

range([start,] stop[, step=1])

1. 這個BIF(Built-in functions)有三個引數,其中用中括號括起來的兩個表示這兩個引數是可選的。

2. step=1 表示第三個引數的預設值是1。

3. range 這個BIF的作用是生成一個從 start 引數的值開始到 stop 引數的值結束的數字序列,該序列包 含 start 的值但不包含 stop 的值。

【例子】

for i in range(2, 9): # 不包含9
print(i)
# 2# 3# 4# 5# 6# 7# 8

【例子】

for i in range(1, 10, 2):
print(i)# 1# 3# 5# 7# 9

3.6 enumerate()函式

enumerate(sequence, [start=0])

1. sequence:一個序列、迭代器或其他支援迭代物件。

2. start:下標起始位置。

3. 返回 enumerate(列舉) 物件

【例子】

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
lst = list(enumerate(seasons))
print(lst)# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')
]
lst = list(enumerate(seasons, start=1)) # 下標從 1 開始
print(lst)# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

用 enumerate(A) 不僅返回了 A 中的元素,還順便給該元素一個索引值 (預設從 0 開始)。此外,用 enumerate(A, j) 還可以確定索引起始值為 j 。

【例子】

languages = ['Python', 'R', 'Matlab', 'C++']

for language in languages:

print('I love', language)

print('Done!')# I love Python# I love R# I love Matlab# I love C++# Done!

for i, language in enumerate(languages, 2):

print(i, 'I love', language)

print('Done!')# 2 I love Python# 3 I love R# 4 I love Matlab# 5 I love C++#Done!

3.7 break 語句

break 語句可以跳出當前所在層的迴圈。

【例子】

import randomsecret = random.randint(1, 10) #[1,10]之間的隨機數while True:
temp = input("猜一猜小姐姐想的是哪個數字?")

guess = int(temp)

if guess > secret:

print("大了,大了")

else:

if guess == secret:

print("你太瞭解小姐姐的心思了!")

print("哼,猜對也沒有獎勵!")

break

else:

print("小了,小了")print("遊戲結束,不玩兒啦!")

3.8 continue 語句

continue 終止本輪迴圈並開始下一輪迴圈。

【例子】

for i in range(10):    

if i % 2 != 0:


print(i)

continue i += 2

print(i)# 2# 1# 4# 3# 6# 5# 8# 7# 10# 9

3.9 pass 語句

pass 語句的意思是“不做任何事”,如果你在需要有語句的地方不寫任何語句,那麼直譯器會提示出錯,而 pass 語句就是用來解決這些問題的。

【例子】

def a_func():# SyntaxError: unexpected EOF while parsing

【例子】

def a_func():

pass

pass 是空語句,不做任何操作,只起到佔位的作用,其作用是為了保持程式結構的完整性。儘管 pass 語句不做 任何操作,但如果暫時不確定要在一個位置放上什麼樣的程式碼,可以先放置一個 pass 語句,讓程式碼可以正常運 行

3.10 推導式

列表推導式

[ expr for value in collection [if condition] ]

【例子】

x = [-4, -2, 0, 2, 4]

y = [a * 2 for a in x]

print(y)# [-8, -4, 0, 4, 8]

【例子】

x = [i ** 2 

for i in range(1, 10)]

print(x)# [1, 4, 9, 16, 25, 36, 49, 64, 81]

【例子】

x = [(i, i ** 2) 

for i in range(6)]

print(x)# [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

【例子】

x = [i for i in range(100) 

if (i % 2) != 0 and (i % 3) == 0]

print(x)# [3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99]

【例子】

a = [(i, j) for i in range(0, 3) 

for j in range(0, 3)]

print(a)# [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

【例子】

x = [[i, j] 
for i in range(0, 3)
for j in range(0, 3)]

print(x)# [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]x[0][0] = 10

print(x)# [[10, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

【例子】

a = [(i, j) 

for i in range(0, 3)

if i < 1 for j in range(0, 3)
if j > 1]
print(a)# [(0, 2)]

元組推導式

( expr for value in collection [if condition] )

【例子】

a = (x for x in range(10))

print(a)

# <generator object <genexpr> at 0x0000025BE511CC48>

print(tuple(a))# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

字典推導式

【例子】

b = {i: i % 2 == 0 for i in range(10)
if i % 3 == 0}

print(b)# {0: True, 3: False, 6: True, 9: False}

集合推導式

{ expr for value in collection [if condition] }

【例子】

c = {i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]}

print(c)# {1, 2, 3, 4, 5, 6}

其它

1. next(iterator[, default]) Return the next item from the iterator. If default is given and the iterator is exhausted, it is returned instead of raising StopIteration.

【例子】

e = (i for i in range(10))

print(e)# <generator object <genexpr> at 0x0000007A0B8D01B0>

print(next(e)) # 0print(next(e)) #
1
for each in e:print(each, end=' ')# 2 3 4 5 6 7 8 9

【例子】

s = sum([i for i in range(101)])

print(s) # 5050

s = sum((i for i in range(101)))

print(s) # 5050

4 異常處理

異常就是執行期檢測到的錯誤。計算機語言針對可能出現的錯誤定義了異常型別,某種錯誤引發對應的異常時, 異常處理程式將被啟動,從而恢復程式的正常執行。

5.1 Python 標準異常總結

1. BaseException:所有異常的 基類

2. Exception:常規異常的 基類

3. SyntaxError:語法錯誤導致的異常

4. IndentationError:縮排錯誤導致的異常

5. ValueError:傳入無效的引數

5.2 Python標準警告總結

1. Warning:警告的基類

2. DeprecationWarning:關於被棄用的特徵的警告

3. FutureWarning:關於構造將來語義會有改變的警告

4. UserWarning:使用者程式碼生成的警告

5. PendingDeprecationWarning:關於特性將會被廢棄的警告

(這些不需要記用到百度即可)

4.3 try - except 語句

try:
檢測範圍except Exception[as reason]: 出現異常後的處理程式碼

try 語句按照如下方式工作:

1. 首先,執行 try 子句(在關鍵字 try 和關鍵字 except 之間的語句)

2. 如果沒有異常發生,忽略 except 子句, try 子句執行後結束。

3. 如果在執行 try 子句的過程中發生了異常,那麼 try 子句餘下的部分將被忽略。如果異常的型別和 except 之後的名稱相符,那麼對應的 except 子句將被執行。最後執行 try - except 語句之後的程式碼。

4. 如果一個異常沒有與任何的 except 匹配,那麼這個異常將會傳遞給上層的 try 中。

【例子】

try:

f = open('test.txt')

print(f.read())

f.close()except OSError:

print('開啟檔案出錯')# 開啟檔案出錯

【例子】

try:

f = open('test.txt')

print(f.read())

f.close()except OSError as error:

print('開啟檔案出錯\n原因是:' + str(error))# 開啟檔案出錯

# 原因是:
[Errno 2] No such file or directory: 'test.txt'

一個 try 語句可能包含多個 except 子句,分別來處理不同的特定的異常。最多隻有一個分支會被執行。

【例子】

try:
int("abc")
s = 1 + '1'
f = open('test.txt')
print(f.read())
f.close()
except OSError as error: print('開啟檔案出錯\n原因是:' + str(error))except TypeError as error: print('型別出錯\n原因是:' + str(error))except ValueError as error: print('數值出錯\n原因是:' + str(error))# 數值出錯# 原因是:invalid literal for int() with base 10: 'abc'

【例子】

dict1 = {'a': 1, 'b': 2, 'v': 22}try:  
x = dict1['y']
except LookupError:
print('查詢錯誤')
except KeyError:
print('鍵錯誤')
else:
print(x)
# 查詢錯誤

try-except-else 語句嘗試查詢不在 dict 中的鍵值對,從而引發了異常。這一異常準確地說應屬 於 KeyError ,但由於 KeyError 是 LookupError 的子類,且將 LookupError 置於 KeyError 之前,因此程式 優先執行該 except 程式碼塊。所以,使用多個 except 程式碼塊時,必須堅持對其規範排序,要從最具針對性的異常 到最通用的異常。

【例子】

dict1 = {'a': 1, 'b': 2, 'v': 22}try:    
x = dict1['y']
except KeyError:
print('鍵錯誤')
except LookupError:
print('查詢錯誤')
else:
print(x)
# 鍵錯誤

【例子】一個 except 子句可以同時處理多個異常,這些異常將被放在一個括號裡成為一個元組。

try:    
s = 1 + '1'

int("abc")

f = open('test.txt')

print(f.read())

f.close()
except (OSError, TypeError, ValueError) as error:
print('出錯了!\n原因是:' + str(error))
# 出錯了!# 原因是:unsupported operand type(s) for +: 'int' and 'str'

4.6 raise語句

Python 使用 raise 語句丟擲一個指定的異常。

【例子】

try:    
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
# An exception flew by!