为什么我不能在这个代码上使用break,而我可以使用什么呢?蟒蛇

时间:2017-03-31 19:41:46

标签: python

我正在做的任务是开发一个程序,识别句子中的单个单词,将它们存储在一个列表中,并将原始句子中的每个单词替换为该单词在列表中的位置。

sentencelist=[] #variable list for the sentences
word=[] #variable list for the words
positions=[]
words= open("words.txt","w")
position= open("position.txt","w")

question=input("Do you want to enter a sentence? Answers are Y or N.").upper()
if question=="Y":
    sentence=input("Please enter a sentance").upper() #sets to uppercase so it's easier to read
    sentencetext=sentence.isalpha or sentence.isspace()
    while sentencetext==False: #if letters have not been entered
        print("Only letters are allowed") #error message
        sentence=input("Please enter a sentence").upper() #asks the question again
        sentencetext=sentence.isalpha #checks if letters have been entered this time

    word = sentence.split(' ')
    for (i, check) in enumerate(word): #orders the words
        print(sentence)

        word = input("What word are you looking for?").upper() #asks what word they want
        if (check == word):
            positionofword=print("your word is in this position:", i+1)
            positionofword=str(positionofword)
        else:
            print("this didn't work") #print error message

elif question=="N":
    print("The program will now close")
else:
print("you did not enter one of the prescribed letters")

words.write(word + " ")
position.write(positionofword + " ")

对我来说问题是我陷入了以下的循环:

   word = input("What word are you looking for?").upper() #asks what word they want
    if (check == word):
        positionofword=print("your word is in this position:", i+1)
        positionofword=str(positionofword)
    else:
        print("this didn't work") #print error message

因此意味着我无法将文字输入文件。我试图使用break,但这对我来说没有用,因为我无法将这些文字放入文件中。

我是这个网站的新手,但我一直在跟踪。希望这是对的,如果我说错了,我愿意听到批评。

1 个答案:

答案 0 :(得分:0)

你在for循环中的逻辑是错误的 - 而不是一次询问用户想要找到的单词,你要求对于句子中的每个单词,只有当他们输入他们想要的单词时才匹配被检查的词。您还要为句子中的每个单词打印一次句子。像这样重组它:

print(sentence)
sentence_words = sentence.split(' ')
word = input("What word are you looking for?").upper() #asks what word they want
for (i, check) in enumerate(sentence_words): #orders the words
    if (check == word):
        print("your word is in this position:", i+1)
        positionofword=i+1
        break
else:
    print("This didn't work")