python 第八天学习笔记
异常处理:
AssertionError 断言assert语句失败
>>> my_list = ["我爱小甲鱼"]
>>> assert len(my_list) >0
>>> my_list.pop() pop() 默认弹出最后一个元素,且删除
'我爱小甲鱼'
>>> assert len(my_list)>0
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
assert len(my_list)>0
AssertionError
AttributeError 尝试访问未知的对象属性
>>> my_list = []
>>> my_list.exe
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
my_list.exe
AttributeError: 'list' object has no attribute 'exe'
IndexError 索引超出序列的范围
>>> my_list = [1,2,3]
>>> my_list[3]
如果想要得到3,应该使用语句my_list[2],因为在python存储中,是第0位,第1位,第2位来存储
Traceback (most recent call last):File "<pyshell#9>", line 1, in <module>
my_list[3]
IndexError: list index out of range
KeyError 字典中查找一个不存在的关键字
>>> my_dict = {"one":1,"two":2,"three":3}
>>> my_dict["one"]
1
>>> my_dict["four"]
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
my_dict["four"]
KeyError: 'four'
NameError 尝试访问一个不存在的变量
>>> my_list
[1, 2, 3]
>>> my_open
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
my_open
NameError: name 'my_open' is not defined
OSError 操作系统产生的异常
SynataxError python语法错误
>>> print"小甲鱼"
SyntaxError: invalid syntax
TypeError 不同类型间的无效操作
>>> 1+"1"
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
1+"1"
TypeError: unsupported operand type(s) for +: 'int' and 'str'
ZeroDivisionError 除数为零
>>> 5/0
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
5/0
ZeroDivisionError: division by zero
检测异常并改正:
try语句检测异常
try-except语句
try:
检测范围
except Exception[as reason]:
出现异常Exception后的处理代码
try:
f = open("1.txt")
print(firead())
f.close()
except OSError as reason:
print("文件出错了\n错误的原因是:"+str(reason))
except TypeError as reason:
print("文件出错了\n错误的原因是:"+str(reason))
求用户输入的数的最大约数,如果是素数就顺便提醒一下“这是一个素数”
def showMaxFactor(num):
count=num//2 //表示整数除法 返回不大于结果的最大整数
while count >1:
if num % count ==0:
print("%d的最大约数是%d"%(num,count))
break
count -=1
else:
print("%d是素数"%num)
num = int(input("请输入一个数:"))
showMaxFactor(num)
try:
int("abc")
except ValueError as reason:
print("出错了"+ str(reason))
else:
print("没有任何问题")
出错了invalid literal for int() with base 10: 'abc'
下次看第10章