如何在捕获其他数据类型时验证用户输入?

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: "))

只要输入是整数(问题陈述明确指出输入是整数),这就很好用。但是,如果我输入 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.")