简体   繁体   中英

What is difference between if (False,) and True == (False,)

I learned python 3 last year, but I have barely experience.

I am reviewing about tuple again.

I would like to figure out difference between if (False,) and True == (False,)

Since if (False,): is true, but True == (False,) is false, I am very confused.

if does not test for == True . It tests for the truth value of an object:

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.

Objects are normally always considered true , except for the False or None objects (on their own), numeric zero, or an empty container.

(False,) is a tuple with one element, and any tuple that is not empty is considered a true value , because it is not an empty container.

You can use the bool() function to get a boolean True or False value for the truth value:

>>> tup = (False,)
>>> bool(tup)
True
>>> bool(tup) == True
True
  1. The boolean value of a tuple is True if it has contents, if it is empty it is False . Because (False,) is a tuple with one element it's boolean value is True .

  2. You are comparing a tuple to a bool , that will always result in False .

Perhaps this highlights the difference.

if (False,): will evaluate because a non-empty tuple is a truth-y value. It is not true itself. And comparing a tuple against a boolean shouldn't be expected to return true in any case, regardless of the content of said tuple.

t = (False,)

print(bool(t)) # True
print(t == True) # False
print(bool(t) == True) # True

For any x whatsoever,

if (x,):

succeeds, because (x,) is a non-empty tuple, and all non-empty tuples evaluate to True in a boolean context.

And again for any x whatsoever,

if True == (x,):

cannot succeed, because the things being compared aren't even of the same types (for a start, True isn't a tuple).

In your question, what I spelled as x you spelled False , but it makes no difference what value x has: False , True , the integer 42, a file object, ..., it doesn't matter.

Not empty values are equivalent to True while empty values are equivalent to False . The tuple (False,) is not an empty tuple so if (False,) always succeeds. On the other hand True is not equal to the singleton tuple (False,) so the logical expression True == (False,) evaluates to False .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM