試圖在我的程式中驗證用戶輸入。
playerChoice = int(input("Enter your choice: "))
while playerChoice != 1 and playerChoice != 2 and playerChoice != 3 and playerChoice !=4:
print("Please make a valid selection from the menu.")
playerChoice = int(input("Enter your choice: "))
只要輸入是整數(問題陳述特別宣告輸入是整數),這就會很好。但是,如果我輸入 1.5 或 xyz,我會得到一個未處理的 ValueError 例外。
所以我改變了它:
try:
playerChoice = int(input("Enter your choice: "))
while playerChoice not in(1, 2, 3, 4):
print("Please make a valid selection from the menu.")
playerChoice = int(input("Enter your choice: "))
except ValueError:
print("Please enter a number.")
playerChoice = int(input("Enter your choice: "))
這也很好用......一次。我知道這里的解決方案很簡單,但我不知道如何將代碼放入一個可以處理其他資料型別的回圈中。我錯過了什么?
抱歉問了這么愚蠢的問題。
uj5u.com熱心網友回復:
這是因為您將try ... except子句放在回圈之外,而您希望它在回圈之內。
playerChoice = None
while not playerChoice:
try:
playerChoice = int(input("Enter your choice: "))
if playerChoice not in(1, 2, 3, 4) :
print("Please make a valid selection from the menu.")
playerChoice = None
except ValueError:
print("Please enter a number.")
uj5u.com熱心網友回復:
將try/except放入回圈中:
while True:
try:
playerChoice = int(input("Enter your choice: "))
if playerChoice not in (1, 2, 3, 4):
print("Please make a valid selection from the menu.")
else:
break
except ValueError:
print("Please enter a number.")
uj5u.com熱心網友回復:
在整個事情上放一個while回圈。
while True:
try:
playerChoice = int(input("Enter your choice: "))
if playerChoice in(1, 2, 3, 4):
break
print("Please make a valid selection from the menu.")
except ValueError:
print("Please enter a number.")
請注意,通過將input()呼叫放在主回圈中,您只需撰寫一次,而不是在所有驗證檢查后重復它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/441318.html
