What is the output of the following code?

What is the output of the following code?

a = 1

b = 0

x = a or b

y = not(a and b)

print(x + y)
A . The program will cause an error
B. 1
C. The output cannot be predicted
D. 2

Answer: D

Explanation:

Topics: logical operators booleans addition operator

implicit type casting

Try it yourself:

a = 1

b = 0

x = a or b

print(x) # 1

print(1 or 0) # 1

y = not(a and b)

print(y) # True

print(1 and 0) # 0

print(not 0) # True

print(x + y) # 2

print(1 + True) # 2

If you calculate with a boolean True becomes the integer 1 and therefore 1 + True is 2

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments