如何在捕获其他数据类型的同时验证用户输入?
尝试验证我的程序中的用户输入。
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: "))
这也很好用......一次。我知道这里的解决方案很简单,但我不知道如何将代码放入处理其他数据类型的循环中。我缺少什么?
抱歉问了这么愚蠢的问题。
Trying to validate user input in my program.
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: "))
This works great as long as the input is an integer (the problem statement specifically states the input is an integer). However, if I enter 1.5 or xyz, I get an unhandled ValueError exception.
So I changed it:
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: "))
which also works great...once. I know the solution here is simple but I can't figure out how to get the code into a loop that will handle other data types. What am I missing?
Sorry for asking such a dumb question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为您将
try ... except
子句放在循环之外,而您希望它位于循环内部。It is because you put the
try ... except
clause outside of the loop, while you want it to be inside of it.将
try
/except
放入循环中:Put the
try
/except
inside your loop:围绕整个事情放置一个 while 循环。
请注意,通过将
input()
调用放在主循环内,您只需编写一次,而不是在所有验证检查后重复它。Put a while loop around the whole thing.
Notice that by putting the
input()
call inside the main loop, you only have to write it once, rather than repeating it after all the validation checks.