Search code examples
pythonpython-3.xisinstance

How do you check if a variable is numeric (without isnumeric) and raise error if it is not in Python?


I don't understand why the following does not operate correctly and raises errors when radius or height are float numbers.

def cone(radius, height):
    if isinstance(radius, int) or isinstance(radius,float) == False:
        raise TypeError("Error: parameters radius and height must be numeric.")
    if isinstance(height, int) or isinstance (height,float)== False:
        raise TypeError("Error: parameters radius and height must be numeric.")

    if radius > 0 and height > 0:
            return ((radius*radius)*(3.1415)*(height/3))
    if radius<=0:
        raise ValueError("Error: radius must be positive.")
    if height <=0:
        raise ValueError("Error: height must be positive.")

Solution

  • Seems like you want

    if not (isinstance(radius, int) or isinstance(radius,float)):
    

    Or actually

    if not isinstance(radius, (float, int)):
    

    Currently your logic is this

    if isinstance(radius, int) or (isinstance(radius,float) == False):
    

    So, if you got an int, then you get the error. If you get a float, you get no error because you end up with False or (True == False)

    Anything or False is the same as bool(Anything), which in this case, True == False, which is False

    Also, I suggest raising all errors and checking conditions first.

    Then just return the actual math because there's no way the variables couldn't be positive at that point