Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty String Boolean Logic

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?

like image 395
Dr.Tautology Avatar asked Jul 18 '26 19:07

Dr.Tautology


2 Answers

to check whether x is True or False:

bool("")
> False

bool("x")
> True

for details on the semantics of is and == see this question

like image 131
scytale Avatar answered Jul 20 '26 08:07

scytale


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.

like image 24
Chickenmarkus Avatar answered Jul 20 '26 09:07

Chickenmarkus