bool? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

bool?

a = 1 b = 2 if bool(a) == bool(b): print(1) else print(0) Solution: 1 I know that bool is Python's true/false equivalent, but as 1 != 2, not sure how this solution turned out to be a 1? As always, any help appreciated.

8th Apr 2019, 9:18 PM
tristach605
tristach605 - avatar
5 Answers
+ 11
bool(0) = false, bool of a number > 0 is true. So, bool(2)=true It seems that there is an implicit conversion of a=1 in true when being compared to bool(2) So, bool(1)==bool(2)=true => print(1)
8th Apr 2019, 10:06 PM
Javier Felipe Toribio
Javier Felipe Toribio - avatar
+ 7
Okay but firstly you need to close the paranthesis behind the a, as in the line "if bool(a==bool(b):"
9th Apr 2019, 5:54 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 4
True can be interpreted as 1 (and False as 0). (bool is a subtype of int btw.) Since b, being not zero, is True, comparing it to 1 gives True again. And bool(True) is True all over again.
8th Apr 2019, 10:10 PM
HonFu
HonFu - avatar
+ 2
Thanks JFT!
8th Apr 2019, 10:10 PM
tristach605
tristach605 - avatar
0
The only values of a boolean variable are true and false. bool(0) is always false and bool of a number > 0 is true, bool(2)=true.
9th Apr 2019, 11:10 PM
Enrique
Enrique - avatar