標籤:hang style werror show except err 錯誤類型 assertion 尋找
1 # !/usr/bin/env python 2 # coding:utf-8 # 編碼 3 4 ‘a test module‘ 5 6 __author__ = ‘Sunflower‘ 7 8 9 # 異常錯誤類型10 # AssertionError 斷句錯誤11 try:12 my_list =[‘zhangsan‘]13 assert len(my_list) > 014 my_list.pop()15 assert len(my_list) > 016 except AssertionError as reason:17 print (‘斷句錯誤‘ + str(reason))18 19 20 # IndexError21 # KeyError 字典的訪問 # my_dict.get(‘four‘)22 # IOError 輸入輸出操作錯誤23 # OSError 作業系統錯誤24 # OverflowError 運算超出限制25 # SyntaxError # 文法26 # TraceError 27 # ZeroDivisionError 除028 # TypeError 類型錯誤29 30 # 調試 try ...except ...finally raise31 try: #先try到錯誤先print,後面的指令不進行32 f = open(‘我是一個檔案.txt‘, ‘r‘)33 print f.read()34 f.close()35 except IOError as reason:36 print(‘檔案出錯‘ + str(reason))37 finally: # 絕對執行38 f.close()39 40 raise IOError(‘檔案出錯‘)41 42 # else43 # if ...else... 要不...要不...44 # while...else... 幹完...幹不完...45 # 尋找最大公約數46 def show_factor(num):47 count = num // 2 # 除248 while count > 1:49 if num % count == 0:50 print(‘%d最大的約數是%d‘ % (num, count))51 break52 count -= 153 else:54 print(‘%d是素數!!‘ % num) # 執行全部執行完了就執行55 56 num = int(33)57 print(show_factor(num))58 # try...else...59 try:60 int(‘abc‘)61 except ValueError as reason:62 print(‘出錯了‘+ str(reason))63 else:64 print(‘沒有出現錯‘)65 66 # with67 try:68 open(‘data.txt‘,‘w‘)69 for each_line in f:70 print(each_line)71 except IOError:72 print(‘出錯了‘)73 finally:74 f.close()
Python學習筆記五:錯誤、調試和測試