Search code examples
pythoncomparison

An and statement returns True when it should return False


Im comparing two strings in an if statement, i expect them both to be False, but one is True.

See code example:

z = 'Test'
x = 'Test1234'

z and x == 'Test'
False

x and z == 'Test'
True

Why? It's not possible that im the first person to see this, but i can't find other threads. I think im using the wrong search words.

Thanks in advance.


Solution

  • Testing a non-boolean variable in an expression is evaluated as a boolean which for a string is True if the String is not None and is not an empty string; e.g. bool('test') = True; bool('') = False; bool(None) = False.

    By default, an object is considered true unless its class defines either a bool() method that returns False or a len() method that returns zero, when called with the object. See built-in types.

    z = 'Test'
    x = 'Test1234'
    
    z and x == 'Test' # False
    x and z == 'Test' # True
    

    The expression x and z == 'Test' using operator precedence is evaluated as x and (z == 'Test') -- adding ()'s for clarity. The lone 'x' is evaluated as a boolean expression so is the same as bool(x) so the expression then becomes bool(x) and (z == 'Test').

    This is evaluated as True and ('Test' == 'Test') or True and True or just True.