Boolean values: Difference between revisions

Add Python
m (added references)
(Add Python)
Line 21:
Everything else is true. Constant <code>True</code> exists.
[http://docs.python.org/reference/expressions.html#boolean-operations]
 
=={{header|Python}}==
Python has a boolean data type with the only two possible values denoted by <code>True</code> and <code>False</code>.
 
The boolean type is a member of the numeric family of types, and when used in a numeric, but not boolean context, <code>True</code> has the value one and <code>False</code> the value zero. Conversely, when numbers are used in a boolean context, zero is False and anything other than zero is True.
 
In a boolean context, Python extends what is meant by true and false by accepting empty collection types, such as an empty dict or an empty list as being False, and non-empty collection types as being True, so in an if statement one might branch on a list which would be the same as testing if the list had any contents.
 
Python has special methods that can be used to set the boolean value of user-created objects too.
 
Some examples:
<lang python>>>> True
True
>>> not True
False
>>> # As numbers
>>> False + 0
0
>>> True + 0
1
>>> False + 0j
0j
>>> True * 3.141
3.141
>>> # Numbers as booleans
>>> not 0
True
>>> not not 0
False
>>> not 1234
False
>>> bool(0.0)
False
>>> bool(0j)
False
>>> bool(1+2j)
True
>>> # Collections as booleans
>>> bool([])
False
>>> bool([None])
True
>>> 'I contain something' if (None,) else 'I am empty'
'I contain something'
>>> bool({})
False
>>> </lang>
 
=={{header|Ruby}}==
Anonymous user