python - 尝试/排除问题
问题描述
我有一个程序可以查看单词列表并告诉用户可以用提供的字母组成的可能单词。我正在尝试使用 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 块内。
推荐阅读
- android - 如何在确定的水平进度条中设置百分比
- c# - VSTS-TFS trigger build limit policy
- android - 为什么我不能让 adb shell top 工作?
- sql-server - INSERT INTO,但保留空白列?
- java - REST 消费者控制台应用程序的 Spring 初始化程序依赖项
- javascript - 反应原生如何在 JSX 中循环查看组件
- asp.net - asp.net Web API 的 LDAP 身份验证
- node.js - Express Simple Auth 不起作用
- html - 使按钮大小与屏幕宽度相同
- jquery - 单击按钮时重新加载数组内容