補充知識點2
接補充知識點1增加以下幾個:
- 錯誤和異常
- 標準庫概覽
1. 錯誤和異常
錯誤分兩種僻他,一種就是你寫錯了缀棍,語法錯誤莺葫,另一種就是異常了
1.1錯誤
語法錯誤就是這個樣子素挽,ide其實會提示你的
if 1 < 2
print('errror')
輸出:
File "D:/python/day009.py", line 1
if 1 < 2
^
SyntaxError: invalid syntax
看看ide的提示:
image.png
告訴你需要一個冒號
處理辦法就是加上冒號就信不過
1.2 異常
在運行它的時候照卦,也有可能發(fā)生錯誤式矫。運行期檢測到的錯誤被稱為異常。
大多數(shù)的異常都不會被程序處理役耕,都以錯誤信息的形式展現(xiàn)在出來
比如:
print(1/0)
結(jié)果:
Traceback (most recent call last):
File "D:/python/day009.py", line 4, in <module>
print(1/0)
ZeroDivisionError: division by zero
除數(shù)不能為0采转,
ZeroDivisionError
是錯誤類型
這樣程序就會中斷運行,所以不能出異常,出了也要去處理
下面通過以下幾個方面來講異常:
- 異常處理
- 拋出異常
- 用戶自定義異常
- 定義清理行為
- 預(yù)定義的清理行為
- assert(斷言)
1.2.1 異常處理
這里就是抓住異常并且處理故慈,用的是
try except
實例1:
while True:
try:
a = int(input('test except:'))
print(a)
print(100/a)
except ZeroDivisionError as err0:
print('Zero:', err0)
except KeyboardInterrupt as err1:
print('\nKey:', err1)
except ValueError as err2:
print('Value:',err2)
else:
print('happy!')
test except:123
123
0.8130081300813008
happy!
test except:aaa
Value: invalid literal for int() with base 10: 'aaa'
test except:0
0
Zero: division by zero
test except:
Key:
test except:
while 千萬不要隨便接受
KeyboardInterrupt
板熊,不然就一直停不下來,很煩
try語句按照如下方式工作察绷;
- 首先干签,執(zhí)行try子句(在關(guān)鍵字try和關(guān)鍵字except之間的語句)
- 如果沒有異常發(fā)生,忽略except子句拆撼,try子句執(zhí)行后結(jié)束容劳。
- 如果在執(zhí)行try子句的過程中發(fā)生了異常,那么try子句余下的部分將被忽略闸度。如果異常的類型和 except 之后的名稱相符竭贩,那么對應(yīng)的except子句將被執(zhí)行。最后執(zhí)行 try 語句之后的代碼莺禁。
- 如果一個異常沒有與任何的except匹配留量,那么這個異常將會傳遞給上層的try中。
- 一個 try 語句可能包含多個except子句哟冬,分別來處理不同的特定的異常楼熄。最多只有一個分支會被執(zhí)行。
- 處理程序?qū)⒅会槍?yīng)的try子句中的異常進行處理柒傻,而不是其他的 try 的處理程序中的異常孝赫。
- 一個except子句可以同時處理多個異常,這些異常將被放在一個括號里成為一個元組红符,例如:
except (ZeroDivisionError,KeyboardInterrupt,ValueError):
pass
pass
是個空語句青柄,為了好看
可以
except
后面不加異常名稱,通配所有異常预侯,然后可以處理致开,想再扔出來就用raise
except:
print('catch error')
raise
最后面可以跟一個
else:
這個看實例1
1.2.2 拋出異常
Python 使用 raise 語句拋出一個指定的異常
例如:
while True:
try:
a = int(input('test except:'))
print(a)
print(100/a)
except:
print('catch error')
raise
結(jié)果:
test except:0
0
catch error
Traceback (most recent call last):
File "D:/python/day009.py", line 10, in <module>
print(100/a)
ZeroDivisionError: division by zero
就這樣子
1.2.3 用戶自定義異常
就是繼承下
Exception
類,并且重寫__str__
函數(shù)
這個樣子:
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
try:
raise MyError(2*2)
except MyError as e:
print('My exception occurred, value:', e.value)
raise MyError('oops!')
結(jié)果:
My exception occurred, value: 4
Traceback (most recent call last):
File "D:/python/day009.py", line 32, in <module>
raise MyError(2*2)
__main__.MyError: 4
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:/python/day009.py", line 35, in <module>
raise MyError('oops!')
__main__.MyError: 'oops!'
一樣被捕獲萎馅,在拋出第一個異常的時候双戳,我觸發(fā)了第二個
想要自己搞個異常模塊的話,可以這樣:
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
上面就是搞個繼承自
Exception
類的類當(dāng)基類糜芳,在擴展
1.2.4 定義清理行為
就是傳說鐘
finally
飒货,就是不管你有沒有異常,最后必須執(zhí)行的地方峭竣,會先執(zhí)行塘辅,然后才會拋出異常,可以用來釋放資源
這個樣子:
while True:
try:
a = int(input('test except:'))
print(a)
print(100/a)
# except:
# print('catch error')
# raise
except ZeroDivisionError as err0:
print('Zero:', err0)
except KeyboardInterrupt as err1:
print('\nKey:', err1)
except ValueError as err2:
print('Value:',err2)
else:
print('happy!')
finally:
print('finally step皆撩;')
輸出:
test except:0
0
Zero: division by zero
finally step扣墩;
test except:
else
是其他異常,finally
就是來兜底的
1.2.5 預(yù)定義的清理行為
這個就是
with
,養(yǎng)成好習(xí)慣呻惕,打開文件用with
荆责,就算是死也會去close
的
格式是這個樣子:
with open("myfile.txt") as f:
for line in f:
print(line, end="")
萬能的
for in
,省的readline
了
1.2.6 斷言
這個其實是一個表達是亚脆,部位真拋出斷言
就這個樣子:
print()
assert True
try:
assert False
except:
print('catch assert')
raise
結(jié)果:
catch assert
File "D:/python/day009.py", line 45, in <module>
assert False
AssertionError
抓的到做院,也拋的出
異常結(jié)構(gòu)
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
2. 標準庫概覽
標準庫嘛,就是到哪都會有的型酥,導(dǎo)入對用模塊就能用
大概介紹下下面幾個常用的:
- 操作系統(tǒng)接口
- 文件通配符
- 命令行參數(shù)
- 錯誤輸出重定向和程序終止
- 字符串正則匹配
- 數(shù)學(xué)
- 訪問 互聯(lián)網(wǎng)
- 日期和時間
- 數(shù)據(jù)壓縮
- 性能度量
- 測試模塊
上面這些基本包含正常操作中都有的
2.1 操作系統(tǒng)接口
這個前面已經(jīng)介紹過了
os
模塊64個接口函數(shù)傳送門
import os
print(os.getcwd())
print(os.listdir())
print(len(dir(os)))
# print(len(str(help(os))))
太多了山憨,就介紹一個
D:\python
['.idea', 'day001.py', 'day002.py', 'day003.py', 'day004.py', 'day005.py', 'day006.py', 'day007.py', 'day009.py', 'test.txt', 'venv', '__pycache__']
150
那個
dir
和help
輸出的太多了查乒。弥喉。。
有個shutil專門做文件和目錄操作
image.png
2.2 文件通配符
glob
模塊提供了一個函數(shù)用于從目錄通配符搜索中生成文件列表:
import glob
print(glob.glob('*py'))
結(jié)果:
['day001.py', 'day002.py', 'day003.py', 'day004.py', 'day005.py', 'day006.py', 'day007.py', 'day009.py']
輸出個list玛迄,可以進行那種批量改名字的操作
2.3 命令行參數(shù)
通用工具腳本經(jīng)常調(diào)用命令行參數(shù)由境。這些命令行參數(shù)以鏈表形式存儲于
sys
模塊的argv
變量。例如在命令行中執(zhí)行"python demo.py one two three"
后可以得到以下輸出結(jié)果:
實例:
import sys
print(sys.version_info)
print(sys.api_version)
print(sys.argv)
結(jié)果:
sys.version_info(major=3, minor=7, micro=4, releaselevel='final', serial=0)
1013
['day009.py', '1', '2', '3', '4', '5', '6', '7', 'haha']
這個之前也介紹過蓖议,敲得命令是
python day009.py 1 2 3 4 5 6 7 haha
輸出也是list虏杰,可以通過這種方式傳配置之類的
2.4 錯誤輸出重定向和程序終止
sys 還有 stdin,stdout 和 stderr 屬性勒虾,即使在 stdout 被重定向時纺阔,后者也可以用于顯示警告和錯誤信息。
就像這樣:
import sys
sys.stderr.write('test err')
sys.exit(-100)
結(jié)果:
test err
Process finished with exit code -100
這里面輸出的是紅色的
test err
哦修然,用sys.exit()
退出笛钝,可以選擇推出返回值
2.5 字符串正則匹配
這里主要是
re
模塊,對于復(fù)雜的匹配和處理愕宋,正則表達式提供了簡潔玻靡、優(yōu)化的解決方案:
這個地方很復(fù)雜,這里簡單介紹中贝,后面專門在探索囤捻,預(yù)留傳送門
大概就這么,最好直接用replace邻寿,簡單粗俗
import re
test_str = 'which foot or or hand fell or fastest'
print(re.findall(r'\bf[a-z]*', test_str))
print(re.sub(r'(\b[a-z]+) \1', r'\1',test_str))
test_str = test_str.replace('or', 'replace')
print(test_str)
結(jié)果:
['foot', 'fell', 'fastest']
which foot or hand fell or fastest
which foot replace replace hand fell replace fastest
2.6 數(shù)學(xué)
2.6.1主要就是math
這個模塊了可以實現(xiàn)c實現(xiàn)的函數(shù)庫
大概這么多:
'__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc'
有些跟數(shù)學(xué)無關(guān)
import math
# print(dir(math))
print(math.sin(30/180*math.pi))
print(math.log(1000,10))
print(type(math.log(1000,10)))
print(int(math.log(1000,10)))
結(jié)果:
0.49999999999999994
2.9999999999999996
<class 'float'>
2
主要三角函數(shù)用弧度來計算
輸出的結(jié)果都是float
型
不要隨便強轉(zhuǎn)蝎土,精度丟失很嚴重
2.6.2 隨機數(shù)
經(jīng)常用的
random()
函數(shù) | 描述 |
---|---|
choice(seq) | 從序列的元素中隨機挑選一個元素,比如random.choice(range(10))绣否,從0到9中隨機挑選一個整數(shù)誊涯。 |
randrange ([start,] stop [,step]) | 從指定范圍內(nèi),按指定基數(shù)遞增的集合中獲取一個隨機數(shù)枝秤,基數(shù)缺省值為1 |
random() | 隨機生成下一個實數(shù)醋拧,它在[0,1)范圍內(nèi)。 |
seed([x]) | 改變隨機數(shù)生成器的種子seed。如果你不了解其原理丹壕,你不必特別去設(shè)定seed庆械,Python會幫你選擇seed。 |
shuffle(lst) | 將序列的所有元素隨機排序 |
uniform(x, y) | 隨機生成下一個實數(shù)菌赖,它在[x,y]范圍內(nèi)缭乘。 |
2.7 訪問 互聯(lián)網(wǎng)
主要是
url
的urllib
和smtp
(郵箱)的smtplib
這個回頭好好研究下,這個這兒玩不了
2.8 日期和時間
主要是datatime 模塊
主要包括下面方法
'MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo'
一些簡單的操作:
import datetime
print(dir(datetime))
print(datetime.date.today())
now = datetime.date.today()
print(now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B."))
birthday = datetime.date(1993,4,17)
print((now-birthday).days)
輸出:
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']
2019-07-15
07-15-19. 15 Jul 2019 is a Monday on the 15 day of July.
9585
都是簡單操作琉用,玩細致要時間
2.9 數(shù)據(jù)壓縮
以下模塊直接支持通用的數(shù)據(jù)打包和壓縮格式:
zlib
堕绩,gzip
,bz2
邑时,zipfile
奴紧,以及tarfile
。
壓縮晶丘,解壓黍氮,crc
import zlib
s = b'xxxxxxxxaaaaaaaabbbbbbbccccccc dddddd 123'
print(len(s))
t = zlib.compress(s)
print(len(t))
r = zlib.decompress(t)
print(str(r))
print(zlib.crc32(s))
結(jié)果:
41
26
b'xxxxxxxxaaaaaaaabbbbbbbccccccc dddddd 123'
3693403203
2.10 性能度量
有些用戶對了解解決同一問題的不同方法之間的性能差異很感興趣。Python 提供了一個度量工具浅浮,為這些問題提供了直接答案沫浆。
from timeit import Timer
a = Timer('a = 2').timeit()
print(a)
結(jié)果:
0.012938772000000001
2.11 測試模塊
doctest
和unittest
回頭再看
文集傳送門 學(xué)習(xí)python100天
整個學(xué)習(xí)python100天的目錄傳送門
無敵分割線
再最后面附上大神的鏈接
這篇跟大神無關(guān),沒有對應(yīng)傳送門