Back to questionsWhat does
JuniorCodeOccasional
What does print(True + 4) output, and why?
Predict the output and explain the type relationship behind it.
print(True + 4)
print(True + True)
print(sum([True, False, True]))Determine the output.
Prints 5, 2, 2. In Python bool is a subclass of int, with True == 1 and False == 0, so booleans participate directly in arithmetic. True + 4 is 1 + 4, and sum of booleans counts the True values. This is why summing a list of conditions counts how many are true.
- Thinking
boolis unrelated tointand cannot do arithmetic - Expecting
True + 4to raise aTypeError - Forgetting
sumof booleans counts theTruevalues
- Why can
Trueand1collapse to one key in adict? - What does
isinstance(True, int)return, and why?