Try/Except 问题

Try/Except Issue

我有一个程序可以查看单词列表并告诉用户可以由提供的字母组成的可能单词。我正在尝试使用 try/except 来解决当用户输入字符串而不是数字后出现 ValueError 时,comp 询问他们希望看到多少个单词。

由于某种原因,except 不起作用,它继续给我一个值错误。有人能告诉我为什么会这样吗?我刚刚了解到 try/except,根据我所见,我认为我没有做错什么。

这是整个程序(以防万一您想查看整个程序而不是 try/except 部分。

def find_words(s, dict_name):
    found_words = []
    mega_list = [] #list with all the words inside

    # make the text dictionary into a list
    #list without new line
    file_obj = open(dict_name, 'r')
    for line in file_obj:
        edit_line = line.strip('\n')
        mega_list.append(edit_line)
         
    
    # find the result
    for word in mega_list:
        temp_list = list(s)
        if len(word)>len(temp_list):
            flag = False #Ignores words that are longer than the temp_list
            continue
        else:
            flag = True
        for letter in word:
            #print(letter) #prints out every letter in these words
            if letter not in temp_list:
                flag=False
                break
            else:
                #print("Before the remove: " + str(temp_list))
                temp_list.remove(letter)
                #print("The list" + str(temp_list)) 

        if flag and (len(temp_list)>=0):
            found_words.append(word)
   
    return found_words

#For every word in word
    #Found_word = True/False (had it as true)
    #for every character in word


def main():
    nums = '1', '2', '3', '4', '5', '6', '7', '8','9', '0'
    letters = input("Please put in a set of letters between 1 and 7 characters long.")
    #print(len(letters))
    while (len(letters) < 1 or len(letters) > 7) or letters.isalpha() == False:
       letters = input("Please put in a set of letters between 1 and 7 characters long.")
    
    count = 0
    num_of_words = int(input("How many words would you like to see displayed?"))
    
    #Won't do the except
    try:
        result = find_words(letters, 'enable1.txt')
        while count < num_of_words:
            print(result[count])
            count+=1
    except ValueError:
        print(find_words(letters, 'enable1.txt'))






main()

我认为问题出在您 运行 以下行:

num_of_words = int(input("How many words would you like to see displayed?"))

您正在请求一个立即转换为 int 的输入,如果该输入不是 int,那么您将触发 ValueError 异常。

此行需要在您的 try/except 块内。