在Python 3中检查多个整数

在Python 3中检查多个整数,python,testing,python-3.x,int,Python,Testing,Python 3.x,Int,最近,我在Python3中发现了一种测试变量是否为int的方法。其语法如下所示: try: a = int(a) except ValueError: print("Watch out! The Index is not a number :o (this probably won't break much in this version, might in later ones though!") error = True 然而,当测试多个变量时,很快就会变得可怕:

最近,我在Python3中发现了一种测试变量是否为int的方法。其语法如下所示:

try:
    a = int(a)
except ValueError:
    print("Watch out!  The Index is not a number :o (this probably won't break much in this version, might in later ones though!")
    error = True
然而,当测试多个变量时,很快就会变得可怕:

def IntegerChecker(a, b, c, d): #A is Index, B is End Time, C is Distance, D is Speed Limit
    global error
    try:
        a = int(a)
    except ValueError:
        print("Watch out!  The Index is not a number :o (this probably won't break much in this version, might in later ones though!")
        error = True
    try:
        b = int(b)
    except ValueError:
        print("Watch out!  The End Time is not a number :o")
        error = True
    try:
        c = int(c)
    except ValueError:
        print("Watch out!  The Distance is not a number :o")
        error = True
    try:
        d = int(d)
    except ValueError:
        print("Watch out!  The Speed Limit is not a number :o")
        error = True
是否有更简单的方法来测试变量是否为整数,如果不是,则将变量更改为true并向用户打印唯一消息

请注意,我在Python方面是一个比较新手的程序员,但是如果有一个更复杂的方法来做这件事,我很想知道。另一方面,在堆栈交换的代码检查部分,这会更好吗?

这是我的解决方案

def IntegerChecker(**kwargs): #A is Index, B is End Time, C is Distance, D is Speed Limit
    error = False
    err = {
        'index': ('Watch out!  The Index is not a number :o (this probably '
                  'won\'t break much in this version, might in later ones though!'),
        'end_time': 'Watch out!  The End Time is not a number :o',
        'distance': 'Watch out!  The Distance is not a number :o',
        'speed': 'Watch out!  The Speed Limit is not a number :o'
    }
    for key, value in kwargs.items():
        try:
            int(value)
        except ValueError:
            print(err.get(key))
            error = True
    return error

IntegerChecker(index=a, end_time=b, distance=c, speed=d)

您不需要为每个变量设置单独的
try-except
块。您可以检查一个变量中的所有变量,如果其中任何变量是非数字的,则会引发异常,并引发错误

def IntegerChecker(a, b, c, d): #A is Index, B is End Time, C is Distance, D is Speed Limit
    global error
    try:
        a = int(a)
        b = int(b)
        c = int(c)
        d = int(d)
    except ValueError:
        print("Watch out!  The Index is not a number :o (this probably won't break much in this version, might in later ones though!")
        error = True

懒散的回答:不要费心测试。如果转换为int导致未经处理的崩溃,则用户通过输入无意义的输入得到了应得的结果。或者,可能对您有用。Fair enough=)但是必须测试所有变量@凯文:数据不是由人输入的,而是由计算机输入的。但是,计算机有时决定不向我发送整数(我无法访问此计算机或其代码)。哦,不管是谁投了反对票,请说明原因。我对这个网站比较陌生,只问了/回答了20个问题。谢谢你,完美地工作了=)将在4分钟内被接受。为什么不只用a、b、c和d作为键?@PadraicCunningham这会更符合逻辑,但是这会使它更容易阅读。你不需要全局,是的,不需要全局,但也不错。嗯,我编辑了代码。恐怕这个答案行不通,因为每次失败我都需要唯一的错误消息。