luci0
luci0

Reputation: 1

confusion while learning and understanding logic in Boolean

In python, Why does (2 == True) #==> False but bool(2) #==> True ? what logic differs between this two why does one provides False whereas the other True .

Upvotes: 0

Views: 30

Answers (1)

Bram van Asseldonk
Bram van Asseldonk

Reputation: 76

In the first case, 2 == True, you are comparing the integer value 2 against the boolean value True. You are essentially asking whether those two are the same. In Python those are not the same, and so the python interpreter returns False.

In the second case, bool(2), you cast the integer to a boolean. You are basically asking, if this was a boolean, what boolean value would it be? In Python, the bool method will always return True, unless:

  • the provided object is empty, like [], {}, ()
  • the provided object is False, like 3 == 4
  • the provided object is 0
  • the provided object is None

Since the integer value 2 is none of the above, bool(2) will return True.

For more information about the bool method, check out this link.

Hope this helps!

Upvotes: 2

Related Questions