3

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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
theeviininja
  • 157
  • 7
  • Given your function names I guess you actually want to test if the input is actually a bool and then convert it to string, you could use `isinstance(bval,bool)` to do that – Some Guy Mar 20 '17 at 03:00

3 Answers3

8

bval is True checks to see whether [1, 2, 3] actually is the True object. You need something like bool() to evaluate whether an object is a true value but not identical to the True object.

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
  • I tried this as well and it works too. Willem's answer below is more in line with what I was taught (so far as the course is only 7 weeks in). – theeviininja Mar 20 '17 at 03:08
2

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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • 1
    This triggered a memory of one of the topics on truthiness. if bval: is correct. It makes sense that I should be checking the argument alone without specifying if it is true. Thanks for the informative answer. It helped me understand. – theeviininja Mar 20 '17 at 03:04
0

[1,2,3] does not equal True, however, if you put in something like 1, then 1 == True would pass but when you use is it will always be False unless it is True

Andria
  • 4,712
  • 2
  • 22
  • 38