如何查找用户输入为整数并使用相同的输入与python中现有的整数值进行比较。
class Error(Exception):
"""This is base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Exception due to Value is too small"""
pass
class ValueTooLargeError(Error):
"""Exception due to Value is too large"""
pass
number = 10
while True:
try:
i_num = int(input("enter number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except (ValueTooSmallError):
print("\nValue is too Small, try again")
except (ValueTooLargeError):
print("\nValue is too Large, try again")
print("congratulations, guessed correctly, i.e.", i_num)
如何通过i_num验证是否应在异常处理中解析是否为整数值。
答案 0 :(得分:2)
如果您要问我们如何知道i_num是否为整数,我们就不知道。由于python变量本质上是动态的,因此输入中传递的任何值都将存储为i_num变量。您必须显式添加验证方法。因为您已经在try块中并且正在使用类型转换,所以在输入不是整数的情况下可以轻松收集任何错误(类型转换不匹配会引发ValueError,因此您可以直接捕获该错误):
while True:
try:
i_num = int(input("enter number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except ValueError as ve:
print("Parameter passed is incorrect "+str(ve))
except (ValueTooSmallError):
print("\nValue is too Small, try again")
except (ValueTooLargeError):
print("\nValue is too Large, try again")
print("congratulations, guessed correctly, i.e.", i_num)