測試題
0.結合你自身的編程經驗,總結下異常處理機制的重要性?
可以增強程序的適應環境的能力,提升用戶體驗。
1.請問以下代碼是否會產生異常,如果會的話,請寫出異常的名稱:
>>> my_list = [1, 2, 3, 4,,]
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)))
TypeError: 'list' object is not callable
3.請問以下代碼是否會產生異常,如果會的話,請寫出異常的名稱:
>>> 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的值。