python-内置函数及捕获异常
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'}
>>> d([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
syntaxerror是什么错误>>> 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,
之后我们做的⼀系列操作不论是否会发⽣错误,抛出异常,都会执⾏内存清理的语句,刷新缓冲区,关闭⽂件等-----------------------------------------------异常------------------------------------------------
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论