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

伊恩·邓恩(Ieuan Dunn)
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**
埃德温·范·米洛(Edwin van Mierlo)

if not True :始终是,False并且您需要“缩小”它,因为它使用了错误的间距,因此下面的打印语句也是如此。

因此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 = []在下一行中将字符串作为输入来执行此操作呢?点击此处查看代码评论

HTH。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档