0
我正在做的任務是開發一個程序,用於識別句子中的單個單詞,將它們存儲在一個列表中,並用該單詞在列表中的位置替換原始句子中的每個單詞。爲什麼我不能在這段代碼上使用break,我可以使用什麼呢? 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,但這對我來說並不奏效,因爲我無法將文字輸入到文件中。
我是這個網站的新手,但我一直在追蹤很長一段時間。希望這是對的,如果我說錯了話,我會接受批評。
移動'打印(句子)'和'字=輸入(「你嚕...'外循環的什麼字 –
斯蒂芬·勞赫如果我這樣做,然後我得到。這句話打印了6次,但它確實與我需要它做的一起工作,我如何避免句子被打印6次? – hana
您是否將循環外的「打印(句子)」移動了? –