1

On rating python quizzes on Solo Learn, I came across a rather puzzling quiz. In it, it assigns booleans to three variables, then prints the sum of them to the console. The answer appears to be consisting of a single character, but I have no idea what it does, and can't find any resources on this.

The code:

a = 4
b = 4
c = 5
x = a == b
y = a == c
a = a != b
puzzle = x + y + a
print (puzzle)

What's going on with this code?

1
  • 2
    booleans are basically integers in Python, whereTrue equals 1 and False equals 0. You can check with print( 1 == True ), which prints True. Jan 12, 2020 at 1:30

2 Answers 2

4

When added, True is converted to 1, and False to 0. Some examples:

print(True + True) # 2

print(True + True + True) # 3

print(False + False) # 0
2

In Python, Booleans are actually Integers under the hood, both False == 0 and True == 1 evaluate to True. So with your code example, puzzle evaluates to 1.

Not the answer you're looking for? Browse other questions tagged or ask your own question.