【Python】程序在運行失敗時,一聲不吭繼續運行pass
阿新 • • 發佈:2017-11-26
pass語句 found col con top path count nts 一聲
在前面程序出現異常時,我們都會給一個提示,告訴用戶,程序為什麽會異常,但是現在我們想在程序出現異常時,不做處理,讓程序默默的往下執行,不要做聲。
那麽我們就引入了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語句還充當了占位符,它提醒你在程序的某個地方什麽都沒有做,並且以後也需要在這裏做什麽。
【Python】程序在運行失敗時,一聲不吭繼續運行pass