【问题标题】:Need some help finishing this function [duplicate]需要一些帮助来完成这个功能[重复]
【发布时间】:2016-10-28 08:16:47
【问题描述】:

假设有三个浮点值通过此函数传递。该函数采用前两个值并从第一个值中减去第二个值。如果该减法的结果小于或等于参数公差的值,则返回 true。我想在那里设置另一个测试。如果传递给它的参数不是浮点数,如何告诉函数返回 None?

def assert_within_tolerance(x_1,x_2,tolerance):
    result=abs(x_1-x_2)
    if result<=tolerance:
        return True
    if result>tolerance:
        print('\nThe result was greater than the tolerance')
        return None

【问题讨论】:

  • isinstance(x_1, float) - True/False 是否是浮点数。
  • 太棒了,我会把这个方法保密的!
  • if not all(isinstance(thing, float) for thing in (x_1,x_2,tolerance)): return

标签: python python-3.x


【解决方案1】:

可以用typeisinstance询问python中变量的类型:

def foo(x,y,z):
    if type(x) is not float or type(y) is not float or type(z) is not float:
        return None
    # normal execution here
    pass

【讨论】:

  • 哇,谢谢。多亏了这一点,我才能够实现单线解决方案。很有用!!!!!!
【解决方案2】:

您可以使用“如果类型(变量)不是浮点数:”。例如

def assert_within_tolerance(x_1,x_2,tolerance):
    if type(x_1) is not float or type(x_2) is not float or type(tolerance) is not float:
        print('\nInputs needs to be float')
        return None
    result=abs(x_1-x_2)
    if result<=tolerance:
        return True
    if result>tolerance:
        print('\nThe result was greater than the tolerance')
        return None

【讨论】:

  • 请注意,这不会接受整数作为输入(没有 3,但 3.0 可以)。您可能需要修改以允许此类输入。
  • 来自the docs for type - The isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-10
  • 2011-04-05
  • 2016-01-11
  • 2020-08-06
  • 1970-01-01
相关资源
最近更新 更多