如何创建一个程序,让用户输入一个句子,然后将该句子放入一个列表,并将每个单词转换为单词的位置

时间:2016-05-27 11:20:25

标签: python-3.4

sentence  = []
sentence = input("Please enter a sentence")                        #asks the user to enter a sentence
for i in range(10):                                                #number of words to be searched for
    search = input("please enter a word to be searched for: ")     #asks for a word to be searched for
    letters = sentence.split(' ')#splits the sentence
    correct = False
    for (i, letters) in enumerate(letters):
        if (letters == search):
            print ("your word has been found in position(s): ")    #prints the position of the words
            print (i)
            works = True #the word has been found
            if not True :
                   print("Sorry this word is not in the sentence ")#prints the word cannot be found**

1 个答案:

答案 0 :(得分:0)

if not True :总是False,你需要“突出”它,因为它使用了错误的间距,所以下面是print语句。

所以if not True :永远不会执行以下操作:

print("Sorry this word is not in the sentence ")

您可能希望将其更改为if not works:,但您没有在任何地方定义works = False,但您确实定义了correct = False,所以也许您在这里混淆了变量的名称。

所以你的代码应该是这样的:

sentence  = []
sentence = input("Please enter a sentence")                        #asks the user to enter a sentence
for i in range(10):                                                #number of words to be searched for
    search = input("please enter a word to be searched for: ")     #asks for a word to be searched for
    letters = sentence.split(' ')#splits the sentence
    correct = False
    for (i, letters) in enumerate(letters):
        if (letters == search):
            print ("your word has been found in position(s): ")    #prints the position of the words
            print (i)
            correct = True #the word has been found
    if not correct :
        print("Sorry this word is not in the sentence ")#prints the word cannot be found**

这应该可行,虽然它可能需要进一步清理,例如:如果你在下一行中输入一个字符串作为输入,为什么要这样做sentence = []。点击此处查看Code Reviews

HTH。