Python 如何返回到代码的开头/创建嵌套循环?
我希望我的代码运行,这样如果条件不满足(在if循环中),它将返回到代码的开头,要求用户输入另一个句子。如何添加这个嵌套循环(如果这就是它的名称) 只要做:Python 如何返回到代码的开头/创建嵌套循环?,python,string,loops,nested,Python,String,Loops,Nested,我希望我的代码运行,这样如果条件不满足(在if循环中),它将返回到代码的开头,要求用户输入另一个句子。如何添加这个嵌套循环(如果这就是它的名称) 只要做: while True: sentence = input("Please input a sentence: ") if sentence.lower() == "quit": break word = input("Please input a word: ") sentence = sentence.low
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))
只要做:
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))
您可以在
的同时在代码周围循环并中断或继续,具体取决于输入:
while True:
sentence = input("Please input a sentence: ")
if bad(sentence): # replace with actual condition
continue
...
for position, w in enumerate(wordlist):
...
break
您可以在的同时在代码周围循环并中断或继续,具体取决于输入:
while True:
sentence = input("Please input a sentence: ")
if bad(sentence): # replace with actual condition
continue
...
for position, w in enumerate(wordlist):
...
break
这绝对是一个无限的过程loop@cricket_007关于你在现已删除的Mohammed答案中的问题,break
位于嵌套的for
循环中,它从for循环中断开,而不是从外部while循环中断开是的,当然……Po可以轻松地询问或退出循环,不是吗?@Aprillion-是的,我意识到就在你发表评论之前,我已经为循环添加了一个出口,这绝对是一个无限的出口loop@cricket_007关于您在现已删除的Mohammed答案中提出的问题,break
位于嵌套的for
循环内,该循环从for循环中断,而不是从while loopYes外部中断,当然……Po可以很容易地请求或退出循环,不是吗?@Aprillion-是的,我意识到就在你评论之前,我已经为循环添加了一个退出