简体   繁体   English

如何确保用户在python中输入一组给定的数字

[英]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.

相关问题 我如何确保用户输入的字符串仅包含数字,运算符和字母Q? - how can i make sure that the user inputs a string containing only numbers, operators, and letter Q? 如何确定参数是否为数字列表? (蟒蛇) - How to make sure if parameter is a list of numbers? (python) 你如何确保用户在创建 object class Python 时输入正确的类型(在我的例子中是列表) - How do you make sure that the user inputs the correct type (list in my case) when creating an object class Python 如何根据用户给出的输入制作二维列表? - How to make the 2- dimensional list from the inputs given by user? 如何进行验证循环以确保用户在 a.split 输入中输入正确的次数? - How do I make a validation loop to make sure the user inputs the correct amount of times in a .split input? 如何让 python 忽略字母,只关注用户输入的数字 - How to make python ignore letters and only focus on numbers from the input given by the user 如何在python 3中使用给定的页面两个输入来搜索每个页面 - How to make search each page with given two inputs of page in python 3 如何确保用户只能在 Python 中输入某些字符? - How to make sure a user can only input certain characters in Python? 给定 python 中字符串中的一组数字 - Given set of numbers in a string in python 如何添加用户在 Python 中输入的一组数字? - How to add a set of numbers that the user inputted in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM