I came across a strange behaviour of python comparing a string with True/False.
I thought that python would print in the following:
if "Test" == True:
print("Hello1")
but it does not. So I wrote some Test cases and I do not understand some of them.
if "Test" == True:
print("Hello1")
if "Test" == False:
print("Hello2")
#This I understand
if bool("Test") == True:
print("Hello3")
#This I understand too
if bool("") == False:
print("Hello4")
if "Test":
print("Hello5")
Output
>> Hello3
>> Hello4
>> Hello5
So I do not understand:
In the first two comparisons, you are checking whether the string "Test"
has the same value as the object True
or False
. This is a value comparison.
If they have a different type, the comparison will return False
. You can see this also when comparing lists, numbers etc.: [1]==1
(false), (1,)==[1]
(false).
In the third and fourth comparisons, you are still doing a value comparison, but since both sides are of the same type (boolean), it will compare the values.
Hello5
is printed because it is not the null string ""
. You can see this by trying "Test" != None
, which returns True
.
While it is a comparison to None
when it comes to most classes(None
is Python's null value), Python's standard data types are compared to their "null" value, which are:
""
for strings,[]
for lists (similary ()
for tuples, {}
for dictionaries),0
for ints and floats,just like a boolean comparison. Therefore it is not wrong to think of if expression
as an implicit cast to if bool(expression)
.
What is going on under the hood is the evaluation of the __non-zero__
(python2.x) or __bool__
(python3.x) method of the class.
In the case of Hello1, Hello2 and Hello5 there is an object comparison and not boolean comparions.
That means that
the string-object "Test"
is not the same as object True
("Hello1")
the string object "Test"
is not the same as object False
("Hello2")
but the string object "Test"
is not None
("Hello5")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With