eval:把字符串轉換成有效表達式
repr:把有效表達式轉換成字符串
round(...)
round(number[, ndigits]) -> number
Round a number to a given precision in decimal digits (default 0 digits).
This returns an int when called with one argument, otherwise the
same type as the number. ndigits may be negative.
pow(x, y, z=None, /)
Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
Some types, such as ints, are able to use a more efficient algorithm when
invoked using the three argument form.
class map(object)
| map(func, *iterables) --> map object
|
| Make an iterator that computes the function using arguments from
| each of the iterables. Stops when the shortest iterable is exhausted.
>>> a
[1, 2, 3]
>>> b
['a', 'b', 'c']
>>> dict(zip(a,b))
{1: 'a', 2: 'b', 3: 'c'}
>>> mylist.extend([1,2,3])
>>> mylist
[2, 1, 3, 2, 1, 4, 3, 2, 1, 'a', 'a', 1, 2, 3]
>>> mylist.append([1,2,3])
>>> mylist
[2, 1, 3, 2, 1, 4, 3, 2, 1, 'a', 'a', 1, 2, 3, [1, 2, 3]]
-------------------------------------------以上是內置函數------------------------------------------
異常,錯誤
程序沒法處理的任務,會拋出異常
錯誤一般是,邏輯錯誤,語法錯誤,無法生成結果等
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> 1 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> if a = b
File "<stdin>", line 1
if a = b
^
SyntaxError: invalid syntax
>>> b[4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
在python中,大部分異常都是基於Exception 這個類
KeyboardInterrupt Exception exit
基類
Exception
python可以通過
try語句檢測異常:
要檢測異常的語句
except 語句來處理異常:
>>> try:
... print(a)
... except NameError:
... print('ABC')
...
ABC
>>> try:
... print(a)
... except Exception as error:
... print(error)
...
name 'a' is not defined
try:
要檢測異常的語句
except 檢測的異常(如果我們使用Execption)則是捕捉所有異常:#但是不建議大家這么做,因為有些異常是我們需要去真實看到的,
執行捕獲異常之后的事情
else:
用來在沒有任何異常情況下執行這里的內容
finally:
不管異常是否發生,這里面寫的語句都會執行
我們一般用來關閉socket,關閉文件,回收線程,進程創建釋放,數據庫連接,mysql句柄,做一些對象內存釋放的工作,
>>> try:
... print(a)
... except Exception:
... print('abc')
... else:
... print('--------')
... finally:
... print('********')
...
abc
********
raise 可以拋出異常
斷言:
assert當判斷的語句為false 那么會拋出一個AssertionError 異常
斷言一般用來判斷一些bool語句,在斷言成功時不采取任何措施,否則觸發AssertionError(斷言錯誤)的異常,
try:
assert 1 == 0
except AssertionError:
print('not equal')
with語句,with語句其實和try,finally語句是一樣的,只不過,他只對支持上下文管理協議(context
management protocol),比如我們的mysql鏈接數據庫,會在完成業務之后他有關閉,打開文件也會有關閉文件,
close()
我們通過with語句打開一個文件對象,如果沒有出錯,文件對象就是file,
之后我們做的一系列操作不論是否會發生錯誤,拋出異常,都會執行內存清理的語句,刷新緩沖區,關閉文件等
-----------------------------------------------異常------------------------------------------------