【发布时间】:2018-09-11 02:34:24
【问题描述】:
我试图在错误类型的数据输入到函数时显示错误消息。在这种情况下,我只是在调用函数时尝试接受int 或float。在函数中输入str 应该会返回错误消息
def isPrime(i):
if not (type(i)==float or type(i)==int):
print("Input wrong type")
return None
i = abs(int(i))
if i == 2 or i == 1:
return True
if not i & 1:
return False
for x in range(3, int(i**0.5) + 1, 2):
if i % x == 0:
return False
return True
# Wanting the code to return an error
isPrime(bob)
【问题讨论】:
-
问题是什么?你的函数表现如何?
-
bob不是一个字符串……它什么都不是,因为你还没有初始化它。试试isPrime('bob')。 -
你不应该使用
type() == typename;一般来说,您应该改用isinstance(input, type)。要给出错误,您想raise错误。在这种情况下,由于类型错误,您可以使用raise TypeError而不是return None。您还可以使用特定的错误消息引发错误,如下所示:raise TypeError('Input must be a float or int') -
我看不出你的代码有什么问题。您将
bob设置为什么?运行代码时会得到什么输出?
标签: python python-3.x