Python automatically casts to boolean if you use another type of variable for a boolean expression.
Here is an example:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
if [1]:
print("Crazy, ")
if 1:
print("this ")
if 2:
print("is ")
if True:
print("also ")
if "a string":
print("true.")
print("")
if not None:
print("This ")
if not False:
print("is ")
if not 0:
print("not ")
if not []:
print("true.")
Everything gets printed.
Now the riddle. What is the output of the following script:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
if None == False:
print("None is false.")
else:
print("None and false are not equal.")
. . . . . . . . . . . . . . . . . . . . . . . .
Answer
None and false are not equal.
Explanation
Although None
and False
evaluate to False
if they are used in a boolean expression, None
is not the same as False
.