2014-04-09 33 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