Search code examples
pythonvalidationtypeslogictypeerror

Why does switching order of OR statement fix TypeError: '<=' not supported between 'str' and 'int'?


I am doing some basic data validation, and I'm confused. I have the following function:

def is_int_gt2(num):
    if num <= 2 or type(num) != int:
        return False
    else:
        return True

When I call is_int_gt2(-1) I get False. And when I call is_int_gt2(5) I get True. So far so good. But if I call is_int_gt2('a'), I get TypeError: '<=' not supported between instances of 'str' and 'int'

What confuses me, however is that when I switch the order of the conditions in the or statement, the function works perfectly!:

def is_int_gt2(num):
    if type(num) != int or num <= 2:
        return False
    else:
        return True

So now I have a working function, but I don't know why. Why does switching the order of the condition fix the function? Thank you.


Solution

  • In your first code block, the num <= 2 expression comes first. When you pass in 'a', python tries to compare 'a' and 2 using <=, resulting in the error.

    But when type(num) != int is first, python checks first the type of a, which is str. And since str != int, the expression is True, breaking out of the if statement; never checking if it was <= 2.