Python输入验证:如何将用户输入限制为特定的整数范围? [英] Python input validation: how to limit user input to a specific range of integers?

查看:3970
本文介绍了Python输入验证:如何将用户输入限制为特定的整数范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是初学者,正在寻找输入验证的信息。

Beginner here, looking for info on input validation.

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

I want the user to input two values, one has to be an integer greater than zero, the next an integer between 1-10. I've seen a lot of input validation functions that seem over complicated for these two simple cases, can anyone help?

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

For the first number (integer greater than 0, I have):

while True:
    try:
        number1 = int(input('Number1: '))
    except ValueError:
        print("Not an integer! Please enter an integer.")
        continue
    else:
        break

这也不会检查它是否为阳性,我想这样做。而且第二个我什么都没有。感谢所有帮助!

This also doesn't check if it's positive, which I would like it to do. And I haven't got anything for the second one yet. Any help appreciated!

推荐答案

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

You could add in a simple if statement and raise an Error if the number isn't within the range you're expecting

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.")

这篇关于Python输入验证:如何将用户输入限制为特定的整数范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆