小甲鱼《零基础学习Python》课后笔记(三十二):异常处理——你不可能总是对的1

测试题
0.结合你自身的编程经验,总结下异常处理机制的重要性?
可以增强程序的适应环境的能力,提升用户体验。

1.请问以下代码是否会产生异常,如果会的话,请写出异常的名称:

>>> my_list = [1, 2, 3, 4,,]  
2.请问以下代码是否会产生异常,如果会的话,请写出异常的名称: ```python >>> my_list = [1, 2, 3, 4, 5] >>> print(my_list(len(my_list))) Traceback (most recent call last): File "
>>> my_list = [3, 5, 1, 4, 2]  
>>> my_list.sorted()  
Traceback (most recent call last):  
	File "<pyshell#4>", line 1, in <module>  
	    my_list.sorted()  
AttributeError: 'list' object has no attribute 'sorted'  
4.请问以下代码是否会产生异常,如果会的话,请写出异常的名称:
>>> my_dict = {'host' : 'http://bbs.fishc.com', 'port' : '80'}  
>>> print(my_dict['server'])  
Traceback (most recent call last):  
	File "<pyshell#6>", line 1, in <module>  
	    print(my_dict['server'])  
KeyError: 'server'  
5.请问以下代码是否会产生异常,如果会的话,请写出异常的名称:
def my_fun(x, y):  
	print(x, y)  
	  
fun(x = 1, 2)  

如果要指定参数需这样写:fun(x = 1, y = 2)。

6.请问以下代码是否会产生异常,如果会的话,请写出异常的名称:

f = open('C:\\test.txt', wb)  
f.write('I love FishC.com!\n')  
f.close()  

异常:

Traceback (most recent call last):  
	File "I:\Python\小甲鱼\test003\test0.py", line 1, in <module>  
	    f = open('C:\\test.txt', wb)  
NameError: name 'wb' is not defined  

因为wb没加单引号,所以Python以为是变量,查找后发现没有定义。

7.请问以下代码是否会产生异常,如果会的话,请写出异常的名称:

def my_fun1():
	x = 5
	def my_fun2():
		x *= x
		return x
	return my_fun2()

my_fun1()

异常:

Traceback (most recent call last):
  File "I:\Python\小甲鱼\test003\test0.py", line 8, in <module>
    my_fun1()
  File "I:\Python\小甲鱼\test003\test0.py", line 6, in my_fun1
    return my_fun2()
  File "I:\Python\小甲鱼\test003\test0.py", line 4, in my_fun2
    x *= x
UnboundLocalError: local variable 'x' referenced before assignment

Python认为在内部函数的x是局部变量的时候,外部函数的x就被屏蔽,所以执行x*=x时,根本找不到局部变量x的值。

猜你喜欢

转载自blog.csdn.net/qq_24546137/article/details/82725468