在前面程序出現異常時,我們都會給一個提示,告訴用戶,程序為什么會異常,但是現在我們想在程序出現異常時,不做處理,讓程序默默的往下執行,不要做聲。
那么我們就引入了pass語句
def count_words(file_path): try: with open(file_path) as file_object: contents = file_object.read() except FileNotFoundError: pass else: #計算該文件包含多少個單詞 words = contents.split() num_words = len(words) print("The file "+" has about " + str(num_words) +" words.") #調用函數 file_paths = ['txt\A.txt','txt\B.txt','txt\C.txt'] for file_path in file_paths: count_words(file_path)
當文件C.txt不存在時,還是執行,只時執行結果沒有任何輸出
pass語句還充當了占位符,它提醒你在程序的某個地方什么都沒有做,並且以后也需要在這里做什么。