我如何返回到我的代码的开始/有一个嵌套循环?

问题描述:

我想我的代码运行,以便如果条件不符合(在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)) 

只要做到:

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

你可以把周围的代码和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