當輸入 (P,p,d,d) 以外的任何內容時,如何讓 while true 回圈繼續運行。當前它僅在輸入 (P,p,d,d) 時重復。如果我以其他方式輸入,它會列印“無效”并進入下一個回圈。
while True:
print("How did you acquire the flat ")
source = input("(Purchased (P) || Produced (D) ) : ")
if ((source != 'P') and (source != 'p') and (source != 'd') and (source != 'D')):
print("\n Invalid Code\n")
break;
while True:
print("\nPlease Select the type of egg ")
type = input("\n (W)et \n (B)ig \n (F)ree \n (O)ld : ")
if (type != 'W' and type != 'B' and type != 'F' and type != 'O' and type != 'w' and type != 'b' and type != 'f' and type != 'o'):
print("\n Invalid Code\n")
break;
uj5u.com熱心網友回復:
while 回圈應該只在輸入是有效代碼時中斷,否則繼續(在列印錯誤訊息后)。您還可以簡化您的 if 陳述句條件 WLOG。
while True:
print("How did you acquire the flat ")
source = input("(Purchased (P) || Produced (D) ) : ")
if source.lower() in ['p', 'd']:
break
print("\n Invalid Code\n")
while True:
print("\nPlease Select the type of egg ")
type = input("\n (W)et \n (B)ig \n (F)ree \n (O)ld : ")
if type.lower() in ['w', 'b', 'f', 'o']:
break
print("\n Invalid Code\n")
最后,您應該避免使用來自內置命名空間的名稱作為變數名稱(type是一個內置函式)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/378050.html
標籤:Python
上一篇:從字符中求和字典中的值
