1. 程式人生 > >小甲魚《零基礎學習Python》課後筆記(三十二)

小甲魚《零基礎學習Python》課後筆記(三十二)

測試題 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的值。