当单词不在句子中时,无法让程序打印"not in sentence"



我有一个程序,它要求输入一个句子,然后要求输入一个单词,并告诉您该单词的位置:

sentence = input("enter sentence: ").lower()
askedword = input("enter word to locate position: ").lower()
words = sentence.split(" ")
for i, word in enumerate(words):
     if askedword == word :
          print(i+1)
    #elif keyword != words :
         #print ("this not")

然而,当我编辑它说如果输入的单词不在句子中,那么打印"this isn't in the sentence"

时,我无法让程序正确工作。

列表是序列,因此您可以对它们使用in操作来测试words列表中的成员。如果在里面,用words.index找到句子里面的位置:

sentence = input("enter sentence: ").lower()
askedword = input("enter word to locate position: ").lower()
words = sentence.split(" ")
if askedword in words:
    print('Position of word: ', words.index(askedword))
else:
    print("Word is not in the given sentence.")

样本输入:

enter sentence: hello world
enter word to locate position: world
Position of word: 1

和,假情况:

enter sentence: hello world
enter word to locate position: worldz
Word is not in the given sentence.

如果你想检查多个匹配,那么enumerate的列表理解是一种方法:

r = [i for i, j in enumerate(words, start=1) if j == askedword]

然后检查列表是否为空并相应地打印:

if r:
    print("Positions of word:", *r)
else:
    print("Word is not in the given sentence.")

Jim的答案——将对askedword in words的测试与对words.index(askedword)的调用结合起来——在我看来是最好和最python化的方法。

相同方法的另一种变体是使用try - except:

try:
    print(words.index(askedword) + 1) 
except ValueError:
    print("word not in sentence")

然而,我只是认为我应该指出OP代码的结构看起来像您可能一直在尝试采用以下模式,这也有效:

for i, word in enumerate(words):
    if askedword == word :
        print(i+1)
        break
else:    # triggered if the loop runs out without breaking
    print ("word not in sentence")

在大多数其他编程语言中都不常见,这个else绑定到for循环,而不是if语句(没错,把你的编辑手从我的缩进中拿开)。参考python.org文档