Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
检查输入是否为介于1和3之间的整数-Python_Python_String_Validation_Python 3.x_Integer - Fatal编程技术网

检查输入是否为介于1和3之间的整数-Python

检查输入是否为介于1和3之间的整数-Python,python,string,validation,python-3.x,integer,Python,String,Validation,Python 3.x,Integer,我希望能够检查输入是否为1到3之间的整数,到目前为止,我有以下代码: userChoice = 0 while userChoice < 1 or userChoice > 3: userChoice = int(input("Please choose a number between 1 and 3 > ")) userChoice=0 当userChoice3时: userChoice=int(输入(“请选择一个介于1和3>之间的数字”) 如果数字不在1和3

我希望能够检查输入是否为1到3之间的整数,到目前为止,我有以下代码:

userChoice = 0

while userChoice < 1 or userChoice > 3:
    userChoice = int(input("Please choose a number between 1 and 3 > "))
userChoice=0
当userChoice<1或userChoice>3时:
userChoice=int(输入(“请选择一个介于1和3>之间的数字”)
如果数字不在1和3之间,这会让用户重新输入一个数字,但我想添加验证,以确保用户不能输入可能导致值错误的字符串或异常字符。

捕获:

当内置操作或函数收到以下参数时引发 具有正确的类型,但值不正确

例如:

while userChoice < 1 or userChoice > 3:
    try:
        userChoice = int(input("Please choose a number between 1 and 3 > "))
    except ValueError:
        print('We expect you to enter a valid integer')

或者尝试比较所需结果中的
输入
,并从循环中中断
,如下所示:

while True:
    # python 3 use input
    userChoice = raw_input("Please choose a number between 1 and 3 > ")
    if userChoice in ('1', '2', '3'):
        break
userChoice = int(userChoice)
print userChoice
使用
Try/Except
是一个很好的方法,但是您的原始设计有一个缺陷,因为用户仍然可以像“1.8”这样输入,它不是一个整数,但会通过您的检查。

如果您使用的是python3,则必须添加标记,因为
input
已从2更改为3
while True:
    # python 3 use input
    userChoice = raw_input("Please choose a number between 1 and 3 > ")
    if userChoice in ('1', '2', '3'):
        break
userChoice = int(userChoice)
print userChoice