Search code examples
pythonif-statementtruthiness

Testing Truthy or Falsy arguments passed through a function into an if statement


I am drawing a blank on this one too. Rather than provide an answer, I would appreciate if someone could help me understand why my code is not printing the expected output:

def bool_to_str(bval):
    if bval is True:
        mytest = 'Yes'
    else:
        mytest = 'No'
    return mytest

Expected output:

>>>bool_to_str([1, 2, 3])
'Yes'
>>>bool_to_str(abcdef)
'Yes'

What's actually output:

>>>bool_to_str([1, 2, 3])
'No'
>>>bool_to_str(abcdef)
'No'

Please help me to understand what I did wrong. I think that the function needs to test the actual truth value of the argument, but I don't understand what I'm missing.


Solution

  • The is checks reference equality, not truthiness. Now clearly [1,2,3] (which is a list object) does not point to the True object (which is bool object). It is hard to say if abcdef which is not defined here points to True. But since you do not provide it, I gonna assume it points to something different.

    Only bool_to_str(True) or bool_to_str(<expr>) where <expr> evaluates to a bool that is True will result in 'Yes' (the bools are singletons, so all Trues are the same object).

    The point is that in order to check the truthness of <expr>, simply write if <expr>:. So in your case it should be:

    if bval:

    You can also - although I advise against it, check the truthness explicitly with bool(..) and check reference equality like:

    if bool(bval) is True:

    Usually it is not a good idea to write is. Only if you want to check if two variables point to the same (i.e. not equivalent) object, or for some singleton objects like True, None, (), etc. it makes really sense.