嘗試向用戶輸入添加驗證。
所以代碼是:
print ('Does this service require an SFP Module? (y/n): ')
while True:
sfpreq = input()
if sfpreq != 'y' or 'n':
print("You must enter either y or n")
continue
else:
break
因此,即使用戶輸入“n”,它也會回傳“print(“您必須輸入 y 或 n”)”并繼續回圈。
我嘗試將變數手動設定為,還嘗試了我在 realpython 上找到的另一個約定,并且還從 while 回圈中洗掉了 if 陳述句:
sfpreq = "n"
if sfpreq != 'y' or sfpreq != 'n':
print("You must enter either y or n")
else:
print("Test")
它再次回傳:
admin@MacBook-Pro Learning Folder % python3 test22.py
You must enter either y or n
我只是在這里遺漏了一些非常基本的東西嗎?
uj5u.com熱心網友回復:
邏輯有問題
sfpreq = "n"
if sfpreq != 'y' or sfpreq != 'n':
print("You must enter either y or n")
else:
print("Test")
在這里,當您進入if回圈時,
sfpreq != 'y'驗證為True并 sfpreq != 'n'驗證為 False。
現在True OR False布爾代數中的陳述句等同于True. 因此,if回圈被執行并被You must enter either y or n列印。在這里查看更多關于布爾代數的資訊
更好的解決方案
sfpreq = "n"
if sfpreq not in {"y","n"}:
print("You must enter either y or n")
else:
print("Test")
所以,在這里我們檢查,如果y還是n不存在的集合{"y","n"}。在這種情況下,sfpreq該集合中是否存在該else陳述句,該陳述句將被執行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/352737.html
