字谜代码中的错误:python

字谜代码中的错误:python,python,Python,这个函数将在一个.txt文件的列表中搜索字谜,我希望能够检查字谜并返回我输入的单词的所有字谜,如果它不是字谜,它将返回输入,当我在下面的代码中执行时,它在for循环中迭代,然后忽略我的第一个if语句,并直接指向我的else语句。我怎样才能解决这个问题 def find_in_dict(): input_word = input("Enter input string)") sorted_word = ''.join(sorted(input_word.strip())) a_word =

这个函数将在一个.txt文件的列表中搜索字谜,我希望能够检查字谜并返回我输入的单词的所有字谜,如果它不是字谜,它将返回输入,当我在下面的代码中执行时,它在for循环中迭代,然后忽略我的第一个if语句,并直接指向我的else语句。我怎样才能解决这个问题

def find_in_dict():

input_word = input("Enter input string)")

sorted_word = ''.join(sorted(input_word.strip()))

a_word = ''.join((input_word.strip()))

word_file = open("filename", "r")

word_list = {}

for text in word_file:
    simple_text = ''.join(sorted(text.strip()))
    word_list.update({text.strip(): simple_text})
alist = []
for key, val in word_list.items():
    if val == sorted_word:
        alist.append(key)
        return alist
    else:
        return "No words can be formed from:" + a_word

您正在if和else分支中生成一个
return
语句,这将中断for(因为函数内部调用的
return
正好执行该操作,中断执行并返回值),因此,不要这样做,只需询问单词是否相等,最后检查是否没有出现(空列表)


使if语句中的条件计算为true-python不仅仅是“跳过”代码。
for text in word_file:
    simple_text = ''.join(sorted(text.strip()))
    word_list.update({text.strip(): simple_text})
alist = []
for key, val in word_list.items():
    if val == sorted_word:
        alist.append(key)

if alist == []: print("No words can be formed from: " + a_word)