2016-12-15 63 views
1

我該如何阻止這個while循環?我如何停止這個while循環python

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") 
+4

請閱讀文檔如何問一個好問題:http://stackoverflow.com/help/how-to-ask – Deadpool

回答

-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

1

當條件滿足時,使用break關鍵字跳出循環。寫短一點,你可以這樣做

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

套裝Sentence到falsy值(False, '', 0),如果你不打算再使用它。