Python 3.6验证整数输入

时间:2017-12-06 15:50:27

标签: python python-3.6

我目前正在使用Python 3.6,我的代码目前要求用户输入2个整数并将它们转换为二进制形式,这不是问题,我遇到的问题是当它要求用户输入数字时,如果他们输入的不是整数,它会破坏代码并产生错误,是否有特定的几行代码可以确保在输入字母或浮点数时不会显示错误?

def add():

    Num1 = int(input("Input the first number between 0 and 255, the calculated answer must not be above 255: "))
    Num2 = int(input("Input the second number between 0 and 255, the calculated answer must not be above 255: "))

我尝试了一种方法:

if type(Num1) != int:
    print("Please input a number")
    add()

但是在测试代码时我仍然会遇到错误。

我希望代码检测到输入了一个字符串或浮点数,然后重新加载" def"函数没有给出语法错误。

这是打印结果:

Print result

1 个答案:

答案 0 :(得分:0)

这是如何从命令行获取整数的要点。它使用while循环和try / except语句。您可以添加整数范围的检查。您可以使用此代码创建一个函数,可以针对您的特定问题调用两次。

n = None
while True:
    n = input('enter an integer')
    try:
        n = int(n)
        break
    except:
        continue
相关问题