异常
语法:
try:
可能发生错误的代码
except:
如果出现异常执行的代码
try:
f = open('test.txt', 'r')
except:
f = open('test.txt', 'w')
捕获指定异常
语法:
try:
可能发生错误的代码
except 异常类型:
如果出现异常执行的代码
try:
print(1/0)
except (NameError, ZeroDivisionError): # 多个指定异常
print('有错误')
try:
print(1/0)
except (NameError, ZeroDivisionError) as result: # 捕获异常描述信息
print(result)
try:
print(num)
except Exception as result: # 捕获所有异常
print(result)
异常的else
else表示没有异常要执行的代码
try:
print(1)
except Exception as result:
print(result)
else:
print('无异常时执行的代码')
异常的finally
finally 表示无论是否异常都要执行的代码,例如关闭文件
try:
f = open('test.txt', 'r')
except Exception as result:
f = open('test.txt', 'w')
else:
print('无异常')
finally:
f.close()
自定义异常
在python中,抛出自定义异常的语法为raise异常类对象
"""
需求:密码长度不足,则报异常(用户输入密码,如果密码长度不足4位,则报错,
即抛出自定义异常,并捕获该异常)
"""
# 自定义异常类,继承Exception
class ShortInputError(Exception):
def __init__(self, length, min_len):
self.length = length
self.min_len = min_len
# 设置抛出异常的描述信息
def __str__(self):
return f'输入长度为{self.length},不能少于{self.min_len}个字符'
def main():
try:
con = input('输入密码:')
if len(con) < 4:
raise ShortInputError(len(con), 4)
except Exception as result:
print(result)
else:
print('密码输入完成')
main()
模块、包
python模块就是一个python文件,以.py结尾,包含python对象定义和python语句。
模块能够定义函数、类和变量,模块里也能包含可执行的代码
导入模块方式:
import 模块名
from 模块名 import 功能名
from 模块名 import *
import 模块名 as 别名
from 模块名 import 功能名 as 别名
制作模块
定义模块:新建一个python文件,命名为module1.py,并定义test函数
def test(a,b):
print(a+b)
# 测试模块,只在当前文件调用该函数,其他导入文件内不符合该条件,不执行test函数调用
if __name__ == 'main':
test(1,1)
注意:
如果使用 from … import … 或 from … import * 导入多个模块的时候,且模块内有同名功能。当调用这个同名功能的时候,调用到的是后面导入的模块的功能。
如果一个模块文件中有__all__变量,当使用from xxx import *导入时,只能导入这个列表中的元素。
__all__ = ['testA']
def testA():
print('testA')
def testB():
print('testB')
包
包将有联系的模块组织在一起,即放在同一个文件夹下,并在这个文件夹下创建一个名为__init__.py文件,那么这个文件夹就称为包。
导入包
import 包名.模块名
包名.模块名.目标