• Martin Thoma
  • Home
  • Categories
  • Tags
  • Archives
  • Support me

Python Puzzle #2: None and False

Contents

  • Answer
  • Explanation

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.

Published

Aug 1, 2012
by Martin Thoma

Category

Code

Tags

  • boolean expression 2
  • Programming 52
  • puzzle 22
  • Python 141

Contact

  • Martin Thoma - A blog about Code, the Web and Cyberculture
  • E-mail subscription
  • RSS-Feed
  • Privacy/Datenschutzerklärung
  • Impressum
  • Powered by Pelican. Theme: Elegant by Talha Mansoor