What is True? What is False?
Written by Gordon Tillman
Thursday, 04 December 2008 15:14
Starting with version 2.2.1, Python got a boolean (bool) datatype. Boolean datatypes have a value of
False. It also has rules for how it evaluates the "truthy-ness" or "falsy-ness" of other things when used in a context where a boolean value is expected.
- All numbers are
True, except for 0.
- All strings are
True, except for the empty string.
- All lists, tuples, and dictionaries are
True, unless they are empty.
How about other objects in general? Well you can define special methods in classes that you create. Here is one in particular:
For an explanation of how this method works:
False, Python calls
x.__nonzero__(), which should return
True or False. When
__nonzero__ is not present, Python calls
__len__ instead, and takes
x.__len__() returns 0. When neither
__len__ is present, Python always considers
x True. (Martelli 2006:108)
Martelli, Alex. (2006) Python in a Nutshell. 2nd edition. Sebastopol, CA: O'Reilly.
Last Updated on Thursday, 04 December 2008 19:43