0

I made a simple print function that just check if 4 * 5 = 20 is True.

Why am I getting False ?

result = 20
Num1 = 4
Num2 = 5

print(Num1*Num2 == result is True)

2 Answers2

3

Check:

result = 20
Num1 = 4
Num2 = 5

print(Num1*Num2 == result is True)
#False
print((Num1*Num2 == result) is True)
#True
print((Num1*Num2) == (result is True))
#False

You could solve it by putting brackets in the right places.

Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34
  • 1
    Your examples are not equivalent to OP's code. What actually happens here is chaining of comparison operators. – interjay Dec 25 '19 at 17:12
  • Yup, you're right- I was wrong about symptoms, I was right about the cure though ;) this kind of proves your point: ```print(False==False is False) #True``` – Grzegorz Skibinski Dec 25 '19 at 17:27
1

Num1*Num2 == result is True is an example of operator chaining, and is equivalent to:

(Num1*Num2 == result) and (result is True)

This is similar to how 1 < x < 10 is equivalent to 1 < x and x < 10. It happens because both == and is are considered comparison operators, and two comparison operators in sequence are chained in this manner.

Since result is True returns False, the overall result is false.

In general, you shouldn't write x is True - just write x. Here: print(Num1*Num2 == result).

interjay
  • 107,303
  • 21
  • 270
  • 254