How to make a python program that lists the positions and displays and error message if not found
Question: I did this code:

    
    
    sentence = input("Type in your sentance ").lower().split()
    Word = input("What word would you like to find? ")
    Keyword = Word.lower().split().append(Word)
    positions = []
    
    for (S, subword) in enumerate(sentence):
        if (subword == Word):
            positions.append
            print("The word" , Word , "is in position" , S+1)
    

But there are 2 problems with it; I dont know how to write a code when the
users word is not found and to but the positions in "The word position is in
[1,3,6,9]. Any help? Thanks


Answer: Your code is having multiple errors. I am pasting here the sample code for
your reference:

    
    
    from collections import defaultdict
    
    sentence_string = raw_input('Enter Sentence: ')
    # Enter Sentence: Here is the content I need to check for index of all words as Yes Hello Yes Yes Hello Yes
    
    word_string = raw_input("Enter Words: ")
    # Enter Words: yes hello
    
    word_list = sentence_string.lower().split()
    words = word_string.lower().split()
    
    my_dict = defaultdict(list)
    for i, word in enumerate(word_list):
         my_dict[word].append(i)
    
    for word in words:
        print "The word" , word, "is in position " , my_dict[word]
    
    # The word yes is in position  [21, 23, 24, 26]
    # The word hello is in position  [22, 25]
    

The approach here is:

  1. Break your sentence i.e `sentence_string` here into list of words
  2. Break your word string into list of words.
  3. Create a dictionary `my_dict` to store all the indexes of the words in `word_list`
  4. Iterate over the `words` to get your result with index, based on the value you store in `my_dict`.

_Note:_ The commented part in above example is basically the output of the
code.

