[英]How do I get my while loop to return to the beginning of the function?
[英]How do i return to the beginning of my code/have a nested loop?
我希望運行我的代碼,以便如果不滿足條件(在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
循環,然后根據輸入break
或continue
:
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 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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.