2014-11-04 44 views
0

多个整数最近我发现测试的方法的变量是否是一个int或没有在Python 3。它的语法是这样的:检查在Python 3

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新手程序员,但如果有一个更复杂的方法来做到这一点,我很想知道这个简洁。另一方面,在Stack Exchange的代码审查部分这会更好吗?

+0

懒惰的答案:不要打扰测试。如果转换为int会导致未处理的崩溃,则用户通过放入无意义的输入来获得他们应得的值。 – Kevin 2014-11-04 16:48:06

+0

或者,[询问用户输入,直到他们给出有效的响应](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response )可能对你有用。 – Kevin 2014-11-04 16:49:07

+0

不够公平=)但是有必要测试所有变量。 @凯文数据不是由人类输入,而是由计算机输入。然而,电脑有时决定不给我一个整数(我没有访问这台电脑或它的代码)。哦,谁下降了,请说明原因。我对这个网站比较陌生,只提问/回答了20个问题。 – 2014-11-04 16:49:09

回答

1

这是我的解决方案

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) 
+0

谢谢你,完美的工作=)将在4分钟内被接受。 – 2014-11-04 16:56:12

+1

为什么不只是使用b c和d作为键? – 2014-11-04 16:56:38

+0

@PadraicCunningham这将更合乎逻辑,但是这使得它必须更易于阅读。 – 2014-11-04 16:58:28

1

你并不需要为每个变量单独try-except块。您可以在一个中检查所有变量,并且如果有任何变量是非数字的,则将引发exception,并抛出error

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 
+0

恐怕这个答案不会工作,因为我需要每个失败的唯一错误消息。 – 2014-11-04 17:12:36