簡體   English   中英

當單詞不在句子中時,無法使程序打印“不在句子中”

[英]Can't get program to print “not in sentence” when word 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")

但是,當我編輯程序以說如果輸入的單詞不在句子中,然后打印“此不在句子中”時,我無法使程序正常工作

列表是序列,因此您可以對它們使用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.

如果您要檢查多個匹配項,那么列表enumerateenumerate是一種解決方法:

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)的調用結合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沒有的一種不同尋常的轉折中, else綁定到for循環,而不綁定到if語句(是的,請讓我的縮進的編輯手)。 請在此處查看python.org文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM