简体   繁体   中英

how do i make my while loop work?

print("sentence analyser")
sentence = input("type in the sentence that you want the program to analyse: ")
keyword = input("type in the word that you want the program to find the position of: ")
sentence = sentence.strip("!£$%^&*()-""_=+[{]}'@#~/?")
sentence = sentence.title()
keyword = keyword.title()
sentence = sentence.split()
while keyword not in sentence:
    keyword = input('word: ')
for (position,words) in enumerate(sentence):
    if (keyword in words): 
         print("the position of your word is",position+1)

whenever i type the a word which is in the sentence it works fine, but when i type a word which is not in the sentence it asks me to input another word(as it should) but when i input a word which is in the sentence it just keeps asking me to input a correct word instead of telling me its position in the sentence> thank you hope you can help

Since you do sentence = sentence.title() all the words are in Title Case. Then when for the first time you ask for a word you do keyword = keyword.title() , so the word is also in Title Case.

But if it doesn't match you only ask for a new word, but don't title() it so it won't match unless you write it in Title Case yourself.

Fix:

while keyword not in sentence:
    keyword = input('word: ').title()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM