+ 2

How does casting works here?

a='a' b=bool(a) print b output-true

21st May 2018, 8:01 AM
Rasik Narula
Rasik Narula - avatar
3 Réponses
+ 25
Anything other than 0, False & None will evaluate true... even bool(0.5) will result true... edit: also empty things will evaluate false... like bool("") = false bool([]) = false.....etc
21st May 2018, 10:10 AM
🌛DT🌜
🌛DT🌜 - avatar
+ 8
So far I see only empty string evaluates to False, any alphanumeric is casted into True, didn't test symbols & punctuation but I guess they too are regarded as True Cmiiw
21st May 2018, 10:11 AM
Ipang
0
In python everything is an object. Objects like 0, None, False as mentioned above are treated as boolean false. Talking about other object imagine that they are just containers. If container is empty (like empty string, or list) it is considered as boolean False: >>> a, b = '', [] >>> bool(a) False >>> bool(b) False If container is NOT empty, it is considered as boolean TRUE, no matter whether it is numeric negative or zero, or space-filled string: >>> x, y = -1, ' ' >>> bool(x) True >>> bool(y) True Even if this container contains an other empty element, the container itself is not empty, so it is consiered as boolean True: >>> wow = [[]] >>> bool(wow) True >>> yay = [[False]] >>> bool(yay) True
22nd May 2018, 2:01 PM
strawdog
strawdog - avatar