Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Kevin Ohlsson
Kevin Ohlsson
4,559 Points

What's the 'philosophical' reason why something empty returns false and something that holds data returns true?

Kenneth introduced the python basic 3 chapter with 'philosophical discussions aside...'.

This made me keen to ask if there some other programming language than python were something 'empty' returns true and something that holds data returns false? Or does this just not make any sense to do?

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

The short answer is convenience. When using the "truthiness" of an object, the code reads smoothly

dic = {}
if dic:
    print("True")
else:
    print("False")

In implementation, object.__bool__() is "[c]alled to implement truth value testing and the built-in operation bool(); should return False or True. When this method is not defined, len() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither len() nor bool(), all its instances are considered true." source doc

A summary of the truth value testing of standard object:

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • None
  • False
  • zero of any numeric type, for example, 0, 0.0, 0j.
  • any empty sequence, for example, '', (), [].
  • any empty mapping, for example, {}.
  • instances of user-defined classes, if the class defines a bool() or len() method, when that method returns the integer zero or bool value False

All other values are considered true — so objects of many types are always true.

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

I can't think of other programming languages where this would be reversed.