1

任务:

  1. 定义一个函数,distance_from_zero一个参数。
  2. 让该函数执行以下操作:
    • 检查它接收的输入的类型。
    • 如果类型是intor float,函数应该返回函数输入的绝对值。
    • 如果类型是任何其他类型,则函数应返回"Not an integer or float!"

我的答案不起作用:

def distance_from_zero(d):
    if type(d) == int or float:
        return abs(d)
    else:
        return "Not an integer or float!"
4

6 回答 6

8

你应该isinstance在这里使用而不是type

def distance_from_zero(d):
    if isinstance(d, (int, float)):
        return abs(d)
    else:
        return "Not an integer or float!"

iftype(d) == int or float总是会True像它被评估的那样float,它是一个True值:

>>> bool(float)
True

帮助isinstance

>>> print isinstance.__doc__
isinstance(object, class-or-type-or-tuple) -> bool

Return whether an object is an instance of a class or of a subclass thereof.
With a type as second argument, return whether that is the object's type.
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
isinstance(x, A) or isinstance(x, B) or ... (etc.).

相关:如何在 Python 中比较对象的类型?

于 2013-05-30T14:05:33.977 回答
7

类型检查应该是

if isinstance(d, int) or isinstance(d, float):

可以缩写

if isinstance(d, (int, float))

您当前的代码正在测试的是

(type(d) == int) or float

或者,用一句话来说:“要么dint,要么float是真的”。由于技术原因,这整个表达式总是正确的。编程语言中的逻辑表达式必须比自然语言更精确地指定。

于 2013-05-30T14:05:50.577 回答
1

您不能使用这种“基于自然语言的逻辑连接”。我的意思是您需要明确说明逻辑条件的各个部分。

if type(d) == int or type(d) == float

这样,您就有了两个比较,它们各自代表:if type(d) == int以及type(d) == float. 其结果可以与or-operator 结合使用。

于 2013-05-30T14:05:47.327 回答
0

这是一个正确的代码:

def distance_from_zero(d):
        if type(d) in (int, float):
                return abs(d)
        else:
                return "Not an integer or float!"

print distance_from_zero(3)
print distance_from_zero(-5.4)
print distance_from_zero("abc")

输出:

3
5.4
Not an integer or float!

请注意缩进,与其他语言相比,Python 中的缩进非常重要。

于 2013-05-30T14:09:39.340 回答
0

在编程中,if 语句不像普通语言那样工作。如果你想说类似的话This fruit is an apple or an orange,你需要把它编程为

if type(fruit) == Apple or type(fruit) == Orange

更具体到您的问题,您想使用isinstance()而不是type(),因为这isinstance()将正确解释子类化。有关更多详细信息,请参阅此答案

所以你应该最终得到类似的东西

def distance_from_zero(d):
    if isinstance(d, int) or isinstance(d, float):
        return abs(d)
    else:
        return "Not an integer or float!"
于 2013-05-30T14:06:35.687 回答
0

您所犯的错误是使用了过多的英文缩写形式。

if type(d) == int or float:

这意味着检查 type isint或 if floatis True,这不是你想要的。

if type(d) == int or type(d) == float:

这将给出所需的结果。

于 2018-01-25T13:38:44.047 回答