需要一些帮助来完成这个功能

时间:2016-06-26 03:23:41

标签: python python-3.x

假设有三个浮点值通过此函数传递。该函数采用前两个值并从第一个值中减去第二个值。如果该减法的结果小于或等于参数容差的值,则返回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

2 个答案:

答案 0 :(得分:0)

您可以使用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

答案 1 :(得分:0)

你可以使用“如果type(variable)不是float:”。例如

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