我如何在python中循环这个循环

时间:2016-12-15 18:42:15

标签: python

如何停止此while循环?

Sentence = input("Please enter the sentence: ").lower()

if "." in Sentence or "'" in Sentence or "," in Sentence or ";" in Sentence or ":" in Sentence or "/" in Sentence or "?" in Sentence or "!" in Sentence or "-" in Sentence:  
    while Sentence:
        print("Your sentence is invalid. Please enter the sentence without punctuation") 
else:
    allWords = Sentence.split()

    print(allWords)

    FindWord = input("Enter the word you are looking for: ").lower()
    for L in range(len(allWords)):
        if FindWord == allWords[L]:
            print("The word <", FindWord, "> is found in", L,"th positions")

3 个答案:

答案 0 :(得分:1)

使用while True: Sentence = input("Please enter the sentence: ").lower() if any(c in Sentence for c in ".',;:/?!-"): print("Your sentence is invalid. Please enter the sentence without punctuation") else: # Accept input break 关键字在条件满足时突破循环。写得有点短,你可以做点像

{{1}}

答案 1 :(得分:1)

如果您不打算重复使用,请将Sentence设置为假值(False, '', 0)

答案 2 :(得分:-2)

Sentence=input("Please enter the sentence: ").lower()

while "." in Sentence or "'" in Sentence or "," in Sentence or ";" in Sentence or ":" in Sentence or "/" in Sentence or "?" in Sentence or "!" in Sentence or "-" in Sentence::    
    print("Your sentence is invalid. Please enter the sentence without punctuation") 
    Sentence=input("Please enter the sentence: ").lower()

使用条件检查是否保持循环。并设置一种方法来改变循环中的Sentence