Reputation:
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
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:
0
, 0L
, 0.0
, 0j
.''
, ()
, []
.{}
.__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
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
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
-
False
itselfNone
''
, 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