0

Pretend there are three float values being passed through this function. The function takes the first two values and subtracts the second from the first. If the result of that subtraction is less than or equal to the value of the parameter tolerance, it returns true. I want to set up another test in there. How do you tell a function to return None if the arguments passed to it are not floats?

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
kjf545
  • 41
  • 8

2 Answers2

0

You can ask the type of a variable in python with type or isinstance:

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
  • Wow thank you. I was able to implement a single line solution thanks to this. Very useful!!!!! – kjf545 Jun 26 '16 at 03:56
0

You can use "if type(variable) is not float:". For example

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
Aguy
  • 7,851
  • 5
  • 31
  • 58
  • Note that this will not accept integers as input (no 3, but 3.0 is ok). You might want to revise to allow such input. – Aguy Jun 26 '16 at 04:00
  • From [the docs for ```type```](https://docs.python.org/3/library/functions.html#type) - ```The isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.``` – wwii Jun 26 '16 at 05:27