2014-04-09 32 views
0

代碼:嘗試/異常流量控制

def get_wordlen(): 
    wordfamily_lst = [] 
    while True: 
     try: 
     word_len = int(input('\nPlease enter length of the word you wish to guess: ')) 
     input_File = open('dic.txt', 'r').read().split() 
     for word in input_File: 
      if len(word) == word_len: 
      wordfamily_lst.append(word) 
      else: 
      print("Sorry, there's no word of that length") 
     continue 

     except ValueError: 
     print('Please enter a numeric value for word length') 
     continue 
     return word_len, wordfamily_lst 

wordlen, wordfamilylst = get_wordlen() 
print(wordlen,wordfamilylst) 

如何修改我的「其他人」的聲明,以防止字長的TXT的用戶輸入。文件不包含。現在,我的代碼將顯示與單詞長度的用戶輸入不匹配的每個單詞的打印語句。

我只想要一個打印語句並循環回到while循環的頂部。

請給我一些建議。

回答

1

您可以修改您的try塊爲:

word_len = int(input('\nPlease enter length of the word you wish to guess: ')) 
    input_File = open('dic.txt', 'r').read().split() 
    wordfamily_lst = [] 
    for word in input_File: 
     if len(word) == word_len: 
     wordfamily_lst.append(word) 
    if not wordfamily_lst: 
     print("Sorry, there's no word of that length") 
    continue 
  • for word in input_File:將文件 在所有單詞執行追加詞來wordfamily_lst僅在長度匹配。
  • 因爲我們現在的while 塊內部分配wordfamily_lst = [],該if not wordfamily_lst:將確保誤差 印刷只有當輸入詞不存在的文件中。

在一個相關的說明,這將是一個好主意,移動代碼讀取while True:塊之外的文件,讀取文件中的所有單詞到一個列表一次,用這個新的列表比較用戶輸入。

總之,這就是我的意思是:

def get_wordlen(): 
    input_file_words = open('dic.txt', 'r').read().split() 
    while True: 
     try: 
     word_len = int(input('\nPlease enter length of the word you wish to guess: ')) 
     wordfamily_lst = [] 
     for word in input_file_words: 
      if len(word) == word_len: 
      wordfamily_lst.append(word) 
     if not wordfamily_lst: 
      print("Sorry, there's no word of that length") 
     continue 

     except ValueError: 
     print('Please enter a numeric value for word length') 
     continue 
     return word_len, wordfamily_lst 

wordlen, wordfamilylst = get_wordlen() 
print(wordlen,wordfamilylst) 
+0

非常感謝你的幫助!你的解釋非常徹底,對於剛開始像我一樣學習計算機科學的人非常有幫助。 – user3454234