[英]How do I validate user input while catching other data types?
嘗試在我的程序中驗證用戶輸入。
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: "))
只要輸入是 integer(問題陳述明確指出輸入是整數),這就很好用。 但是,如果我輸入 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: "))
這也很好用……一次。 我知道這里的解決方案很簡單,但我不知道如何將代碼放入處理其他數據類型的循環中。 我錯過了什么?
很抱歉問了這么愚蠢的問題。
將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.")
把整個事情放在一個 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()
調用放在主循環中,您只需編寫一次,而不是在所有驗證檢查之后重復它。
這是因為您將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.")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.