Python输入验证:如何将用户输入限制为特定的整数范围?

时间:2017-01-24 15:57:03

标签: python validation exception input exception-handling

初学者,寻找有关输入验证的信息。

我希望用户输入两个值,一个必须是大于零的整数,下一个是1-10之间的整数。我已经看到很多输入验证函数对于这两个简单的情况看起来过于复杂,有人可以帮忙吗?

对于第一个数字(大于0的整数,我有):

$1                       Inserts the first group, the first ( )
page/                    Followed by the string "page/"
$3                       Followed the third group

这也不会检查它是否是正面的,我希望它能做到。我还没有为第二个得到任何东西。任何帮助表示赞赏!

3 个答案:

答案 0 :(得分:3)

您可以添加简单的if语句,如果数字不在您期望的范围内,则引发错误

while True:
    try:
        number1 = int(input('Number1: '))
        if number1 < 1 or number1 > 10:
            raise ValueError #this will send it to the print message and back to the input option
        break
    except ValueError:
        print("Invalid integer. The number must be in the range of 1-10.")

答案 1 :(得分:1)

使用assert

while True:
    try:
        number1 = int(input('Number1: '))
        assert 0 < number1 < 10
    except ValueError:
        print("Not an integer! Please enter an integer.")
    except AssertionError:
        print("Please enter an integer between 1 and 10")
    else:
        break

答案 2 :(得分:0)

        String strJson = "[{ \"art_src_path\": \"source/subdir/hi-there.txt\",\"art_id\": \"6945-L9.txt\",\"art_date\": \"2018:03:10 01:10:33\"},"+
"{ \"art_src_path\": \"source/hello-world.txt\",\"art_id\": \"10426-L13.txt\",\"art_date\": \"2018:03:10 01:10:33\"},"+
"{ \"art_src_path\": \"source/subdir/testfile.txt\",\"art_id\": \"50518-L66.txt\",\"art_date\": \"2018:03:10 01:10:33\"}]" ;

        System.out.println("input = "+strJson) ;

        JSONParser parser = new JSONParser() ;
        JSONArray a = (JSONArray) parser.parse(strJson) ;

        for (Object o:a) {
            String path = (String) ((JSONObject) o).get("art_src_path") ;
            System.out.println("source path:"+path) ;
        }