gpt4 book ai didi

python - 在 Python 3 中检查多个整数

转载 作者:行者123 更新时间:2023-11-28 21:11:19 25 4
gpt4 key购买 nike

最近发现了一种在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 的代码审查部分会更好吗?

最佳答案

这是我的解决方案

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)

关于python - 在 Python 3 中检查多个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26740520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com