4

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().

2
  • 1
    Could you please elaborate on what you're trying to ask? By maybe adding some code examples. Commented May 9, 2013 at 7:01
  • 0 and 0.0 don't evaluate to True Commented May 9, 2013 at 7:01

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I think you mean non-zero numbers.
Adding on your answer. string can be checked through a similar way. So, it's not only integers and floats.
4

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.

Comments

4

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.

Comments

0

0 is evaluated to False.

if 0: 
    assert(0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.