I searched daniweb for related questions and google but i canot seem to find my problem in my code
When I try to search for a word that exists in my list it returns false

This is my code

def main():
    #the word that I am looking for
    word = "fox"

    #opening my dictionary file
    dict = open("src/DictionaryE.txt","r")

    #add the file to a list
    for i in dict:

        list =[]
    #geting rid of formating


        print list
    #searching for the word in list
    if word in list:
    #if the word is in the list print it    
        print word
        print "You typed a word that dosen't exist"


My dictionary is a simple txt file with 3 words


Oh and the txt file is read and printed correctly so no I/O error

If any one knows whatI am doing wrong please tell me

Thank you

Dont use list and dict as variable names,words are reseverd bye Python.
To clean it up.

my_file = open("words.txt")
lst = [] #Outside the loop
for word in my_file:
    word = word.strip()

#searching for the word in list
search_word = "fox"
if search_word in lst:
    print 'Word found: <{}>\nDictionary {}'.format(search_word, lst)
    print "You typed a word that dosen't exist"

Word found: <fox>
Dictionary ['bear', 'wolf', 'fox']

Don't place all code in one big function.
Do some execerice on function,and try to keep function small and do a specific task and return result out.
This make code eaiser to read an test.

def read_contend(dictionary):
    '''Read contend and return a list'''
    with open(dictionary) as f_obj:
        word_lst = [word.strip() for word in f_obj]
        return word_lst

def search_contend(search_word, word_lst):
    '''Search for a word in input contendt'''
    if search_word in word_lst:
        return search_word
    return "You typed a word that dosen't exist"

if __name__ == '__main__':
    dictionary = 'words.txt'
    search_word = "fox"
    word_lst = read_contend(dictionary)
    print search_contend(search_word, word_lst)

Edited 2 Years Ago by snippsat



immediately before line 19 and post the output here.

Also 'list' and 'dict' are so common words in python that nobody uses them for variables.

Thank you for your input I will create a function for each task and keep it small

This question has already been answered. Start a new discussion instead.