Boolean weirdness?


#1



a = True
b = False
c = "True"
d = "False"
print c + d
print a + b

Expected TrueFalse for c + d
Did not expect 1 for a + b


#2

Can you post the link to this exercise? This code isn't part of the 'Tip Calculator' Lesson.


#3

There isn't one. It isn't part of the exercise, just playing with my new found knowledge of variables to see what happens.


#4

That error then is possibly because of the exercise you are using them in. If you want to use code completely unrelated to an exercise, it's better if you do it on a separate program.


#5

a
True
b
False
c = "True"
d = "False"
a
True
b
False
c
'True'
d
'False'
c + d
'TrueFalse'
a + b
1

From my own Python console.


#6

Found the answer on Reddit.

True is a Boolean, but it has an Int value of 1, just as False has in Int value of 0.

It is adding 1 + 0 and getting 1, which makes perfect sense.

:slight_smile:


#7

Ah, never knew that. Was just as confused as you were :joy:


#8

Indeed, this is legacy behavior. There used to be no True or False, 1 and 0 were used But when introducing True and False, to prevent old code from breaking they made it like it is. To take it one further to your examples:

>>> isinstance(True, bool)
True
>>> isinstance(True, int)
True
>>> isinstance(False, bool)
True
>>> isinstance(False, int)
True

For when you get on to classes, bool inherits from int.


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.