多个整数最近我发现测试的方法的变量是否是一个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的代码审查部分这会更好吗?
懒惰的答案:不要打扰测试。如果转换为int会导致未处理的崩溃,则用户通过放入无意义的输入来获得他们应得的值。 – Kevin 2014-11-04 16:48:06
或者,[询问用户输入,直到他们给出有效的响应](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response )可能对你有用。 – Kevin 2014-11-04 16:49:07
不够公平=)但是有必要测试所有变量。 @凯文数据不是由人类输入,而是由计算机输入。然而,电脑有时决定不给我一个整数(我没有访问这台电脑或它的代码)。哦,谁下降了,请说明原因。我对这个网站比较陌生,只提问/回答了20个问题。 – 2014-11-04 16:49:09