尝试/异常流量控制

时间:2014-04-09 19:58:25

标签: python-3.x

代码:

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的语句。文件不包含。现在,我的代码将显示每个单词的print语句,该单词与用户输入的字长不匹配。

我只想要一个print语句并循环回while循环的顶部。

请给我一些建议。

1 个答案:

答案 0 :(得分: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
  • 由于我们现在在wordfamily_lst = []内分配while 阻止,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)