零基础学习Python 作业 第32章

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

my_list = [1,2,3,4,,]

SyntaxError: invalid syntax 无效的语法

 

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

>>> my_list = [1,2,3,4,5]
>>> print (my_list[len(my_list)])

Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
print (my_list[len(my_list)])
IndexError: list index out of range  索引错误:列表索引超出范围

 

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

>>> my_list = [3,5,1,4,2]
>>> my_list.sorted()

Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
my_list.sorted()
AttributeError: 'list' object has no attribute 'sorted'   'list'对象没有'已排序'属性
>>>

sorted是内置函数bif,不能用.调用方法调用内置函数!

>>> sorted(my_list)
[1, 2, 3, 4, 5]
>>>

4.写出异常名称:

>>> my_dict = {'host':'http://bbs.fishc.com','port':'80'}
>>> print(my_dict['server'])

Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
print(my_dict['server'])
KeyError: 'server'   
>>>

尝试访问一个不存在的健值,引发的 keyerror  异常,为了避免这个异常可以使用 my_dict.get('server')

>>> my_dict.get('server')
>>> my_dict
{'host': 'http://bbs.fishc.com', 'port': '80'}
>>> 使用get不存在时不报错!

5.写出异常名称:

>>> def my_fun(x,y):
print (x,y)
f(x=1,2)

SyntaxError: non-keyword arg after keyword arg
>>>

如果使用关键字参赛的话,需要  f(x=1,y=2)

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

>>> f = open('c:\\test.txt',wb)

Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
f = open('c:\\test.txt',wb)
NameError: name 'wb' is not defined
>>>wb应该是字符串没有加‘’

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

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

x *= x
UnboundLocalError: local variable 'x' referenced before assignment 局部变量错误
闭包,Python认为在内部函数的x是局部变量的时候,外部函数x就被屏蔽起来了,所以只需x*=x的时候
在右边根本就找不到局部变量x的值,因此报错。
Python3中 增加nonlocal:
def my_fun1():
x = 5
def my_fun2():
nonlocal x
x *= x
return x
return my_fun2()
my_fun1()

 

posted @ 2018-11-14 10:09  蘑菇慢慢  阅读(88)  评论(0)    收藏  举报