I just stumbled across this and I couldn't find a sufficient answer:
x = ""
Why then is:
x == True
False
x == False
False
x != True
True
x != False
True
Am I supposed to conclude that x is neither True nor False?
to check whether x is True or False:
bool("")
> False
bool("x")
> True
for details on the semantics of is and == see this question
Am I supposed to conclude that x is neither True nor False?
That's right. x is neither True nor False, it is "". The differences start with the type:
>>> print(type(""), type("x"), type(True), type(False))
builtins.str, builtins.str, builtins.bool, builtins.bool
Python is a highly object oriented language. Hence, strings are objects. The nice thing with python is that they can have a boolean representation for if x: print("yes"), e. g.. For strings this representation is len(x)!=0.
1 == 1.0 even though they're int and float, respectively.__bool__(self). Furthermore, objects of arbitrary types can be compared w. r. t. equality (==) by the magic method __equal__(self, other).is) and the equality (==). While 1 and 1.0 are equal (1 == 1.0), they will never have the same identity due to the different types.is is a whole other deal. (1, 2) is (1, 2) can be true or false.In a Boolean context, null / empty strings are false (Falsy). If you use
testString = ""
if not testString:
print("NULL String")
else:
print(testString)
As snakecharmerb said, if you pass the string to the bool() function it will return True or False based
>>> testString = ""
>>> bool(testString)
False
>>> testString = "Not an empty string"
>>> bool(testString)
True
See this doc on Truth Value Testing to learn more about this:
Python 2:
https://docs.python.org/2/library/stdtypes.html#truth-value-testing
Python 3:
https://docs.python.org/3/library/stdtypes.html#truth-value-testing
x represents an empty string literal object. By itself it is not a boolean type value, but as the other answers suggest a "cast" to boolean is possible. When used in an if statement condition check expression, the expression will evaluate to "False-y" due to the string being empty.
However your comparison examples compare the object x to the singleton objects "True" and "False", which falls back to a "is" comparison. Since the objects are different, the compare evaluates to False for when checking equality.
(For details look at Returning NotImplemented from __eq__ )
xisn't equal to eitherTrueorFalse. Why did you think it would be? Have you been confused somehow by docs.python.org/2/library/stdtypes.html#truth-value-testing? It will still evaluate false-y in a boolean context:if x:,bool(x), etc..bool(x) == False. Username checks out, though.x=0. And then do the same thing withx=1.