最近我发现了一种在Python 3中测试变量是否为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中的新手程序员,但如果有一个更复杂的方法来做到这一点,我很想知道。另外,在Stack Exchange的代码审查部分,这会更好吗?
答案 0 :(得分: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)
答案 1 :(得分: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