检查多种类型的变量类型不会产生预期的结果

0 python types boolean-logic if-statement

任务:

  1. distance_from_zero使用一个参数定义一个函数.
  2. 具有该功能执行以下操作:
    • 检查它收到的输入类型.
    • 如果类型为intfloat,则函数应返回函数输入的绝对值.
    • 如果类型是任何其他类型,则函数应返回 "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!"
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 6

你应该isinstance在这里而不是type:

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

if type(d) == int or float总是会True被评估为float,它是一个True值:

>>> bool(float)
True
Run Code Online (Sandbox Code Playgroud)

帮助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.).
Run Code Online (Sandbox Code Playgroud)

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


Fre*_*Foo 6

类型检查应该是

if isinstance(d, int) or isinstance(d, float):
Run Code Online (Sandbox Code Playgroud)

可以缩写

if isinstance(d, (int, float))
Run Code Online (Sandbox Code Playgroud)

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

(type(d) == int) or float
Run Code Online (Sandbox Code Playgroud)

或者,用文字表示:"要么类型dint,要么float是真的".由于技术原因,这整个表达始终是正确的.编程语言中的逻辑表达式必须比自然语言更精确地指定.