2016-02-05 49 views
0

我想我的代碼運行,以便如果條件不符合(在if循環中)它將返回到代碼的開頭,要求用戶輸入另一個句子。我如何添加這個嵌套循環(如果這就是它所謂的)?我如何返回到我的代碼的開始/有一個嵌套循環?

sentence = input("Please input a sentence: ") 
word = input("Please input a word: ") 
sentence = sentence.lower() 
word = word.lower() 
wordlist = sentence.split(' ') 
print ("Your word, {0}, is in positions:".format (word)) 
for position,w in enumerate(wordlist): 
    if w == word: 
     print("{0}".format(position+1)) 

回答

0

只要做到:

while True: 
    sentence = input("Please input a sentence: ") 
    if sentence.lower() == "quit": break 
    word = input("Please input a word: ") 
    sentence = sentence.lower() 
    word = word.lower() 
    wordlist = sentence.split(' ') 
    print ("Your word, {0}, is in positions:".format (word)) 
    for position,w in enumerate(wordlist): 
     if w == word: 
      print("{0}".format(position+1)) 
+0

這絕對是一個無限循環 –

+0

@ cricket_007關於你在現在刪除的穆罕默德答案中的問題,「break」在嵌套的for循環中,並且出於for循環而不是ou t的外圍while循環 – Aprillion

+0

是的,當然... Po可以很容易地詢問或退出循環,不是嗎? – Clodion

2

你可以把周圍的代碼和breakcontinue一個while迴路根據輸入:

while True: 
    sentence = input("Please input a sentence: ") 
    if bad(sentence): # replace with actual condition 
     continue 
    ... 
    for position, w in enumerate(wordlist): 
     ... 
    break