user2260218
user2260218

Reputation:

Python Boolean Values

Why is it that in Python integers and floats are, without being evaluated in a boolean context, equivalent to True? Other data types have to be evaluated via an operator or bool().

Upvotes: 4

Views: 6940

Answers (4)

fenmarel
fenmarel

Reputation: 363

From Python Documentation 5.1:

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, 0L, 0.0, 0j.
  • any empty sequence, for example, '', (), [].
  • any empty mapping, for example, {}.
  • instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False.

Why? Because it's handy when iterating through objects, cycling through loops, checking if a value is empty, etc. Overall, it adds some options to how you write code.

Upvotes: 4

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

That's not True:

>>> print("True" if 1 else "False")
True
>>> print("True" if 0 else "False")
False
>>> print("True" if 0.0 else "False")
False
>>> print("True" if 123.456 else "False")
True
>>> print("True" if "hello" else "False")
True
>>> print("True" if "" else "False")
False
>>> print("True" if [1,2,3] else "False")
True
>>> print("True" if [] else "False")
False
>>> print("True" if [[]] else "False")
True

Only non-zero numbers (or non-empty sequences/container types) evaluate to True.

Upvotes: 6

Bibhas Debnath
Bibhas Debnath

Reputation: 14929

Here is a use case -

>>> bool(2)
True
>>> bool(-3.1)
True
>>> bool(0)
False
>>> bool(0.0)
False
>>> bool(None)
False
>>> bool('')
False
>>> bool('0')
True
>>> bool('False')
True
>>> bool([])
False
>>> bool([0])
True

In Python, these are False -

  • The Boolean value False itself
  • Any numerical value equal to 0 (0, 0.0 but not 2 or -3.1)
  • The special value None
  • Any empty sequence or collection, including the empty string('', but not '0' or 'hi' or 'False') and the empty list ([], but not [1,2, 3] or [0])

Rest would evaluate to True. Read more.

Upvotes: 4

jimifiki
jimifiki

Reputation: 5534

0 is evaluated to False.

if 0: 
    assert(0)

Upvotes: 0

Related Questions