[英]how to make sure user inputs a given set of numbers in python
I am trying to make a program in python in which a user can only input 1, 2 or 3. I tried this method but it does not work.`我正在尝试用 python 制作一个程序,其中用户只能输入 1、2 或 3。我尝试过这种方法,但它不起作用。`
x = input("Enter your Choice: ")
while (x!=1 or x!=2 or x!=3):
x = input("Enter your Choice: ")
Using this method it continually asks for input even if 1, 2 or 3 or any other number is keyed in. Can anybody tell please tell me why this does not work and also suggest a correct way to enter these three numbers.使用这种方法,即使输入了 1、2 或 3 或任何其他数字,它也会不断要求输入。谁能告诉我为什么这不起作用,并建议输入这三个数字的正确方法。
This is what we call a logic error .这就是我们所说的逻辑错误。
The line should be like this:该行应该是这样的:
while (x!=1 and x!=2 and x!=3):
That is, change the or to and .也就是说,将or更改为and 。
To handle any input and give out the error if it's not 1,2 or 3, do this:要处理任何输入并在它不是 1,2 或 3 时发出错误,请执行以下操作:
x = raw_input("Enter your Choice: ")
while (x!='1' and x!='2' and x!='3'):
x = raw_input("Enter your Choice: ")
Try:尝试:
def userchoicevalidator():
x = input("Please Enter Your Choice: ")
while x not in list('123'):
x = input("Please Enter Your Choice: ")
the reason that raw_input
wasn't working for you is because it has been deprecated in python 3. input
is in python 3. Also note that this returns a string, not an integer, which is why your booleans checks were failing unexpectedly raw_input
对您不起作用的原因是它在 python 3 中已被弃用。 input
在 python 3 中。另请注意,这返回一个字符串,而不是一个整数,这就是为什么您的布尔值检查意外失败的原因
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.