Python Boolean: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
(Created page with "=Internal= * Python Language =Overview= <syntaxhighlight lang='python'> x = True type(x) <class 'bool'> </syntaxhighlight> =Operators= ==OR <tt>|</...")
 
Tag: Manual revert
 
(9 intermediate revisions by the same user not shown)
Line 2: Line 2:
* [[Python_Language#Boolean|Python Language]]
* [[Python_Language#Boolean|Python Language]]
=Overview=
=Overview=
A boolean can be <code>True</code> or <code>False</code>.
<syntaxhighlight lang='python'>
<syntaxhighlight lang='python'>
x = True
x = True
Line 7: Line 8:
<class 'bool'>
<class 'bool'>
</syntaxhighlight>
</syntaxhighlight>
=What is True?=
The following values evaluate to <code>False</code> in Python. Everything else evaluates to <code>True</code>.
* boolean <code>False</code>
* <code>None</code>
* zero integer <code>0</code>
* zero float <code>0.0</code>
* empty string <code>''</code>
* empty list <code>[]</code>
* empty tuple <code>()</code>
* empty dict <code>{}</code>
* empty set <code>set()</code>
=Operators=
=Operators=
==OR <tt>|</tt> and <tt>|=</tt>==
==OR: <tt>|</tt> and <tt>|=</tt>==
<syntaxhighlight lang='py'>
assert (True | True)
assert (True or True)
assert (True | False)
assert (True or False)
assert (False | True)
assert (False or True)
assert not (False | False)
assert not (False or False)
</syntaxhighlight>
 
<syntaxhighlight lang='py'>
l = [True, False]
b = False
for e in l:
    b |= e
assert b
 
l = [False, False]
b = False
for e in l:
    b |= e
assert not b
</syntaxhighlight>
 
Note that <code>+</code> applied to booleans contest to integers.
==AND: <tt>&</tt> and <tt>&=</tt>==
<syntaxhighlight lang='py'>
assert (True & True)
assert (True and True)
assert not (True & False)
assert not (True and False)
assert not (False & True)
assert not (False and True)
assert not (False & False)
assert not (False and False)
</syntaxhighlight>

Latest revision as of 19:56, 16 May 2024

Internal

Overview

A boolean can be True or False.

x = True
type(x)
<class 'bool'>

What is True?

The following values evaluate to False in Python. Everything else evaluates to True.

  • boolean False
  • None
  • zero integer 0
  • zero float 0.0
  • empty string
  • empty list []
  • empty tuple ()
  • empty dict {}
  • empty set set()

Operators

OR: | and |=

assert (True | True)
assert (True or True)
assert (True | False)
assert (True or False)
assert (False | True)
assert (False or True)
assert not (False | False)
assert not (False or False)
l = [True, False]
b = False
for e in l:
    b |= e
assert b

l = [False, False]
b = False
for e in l:
    b |= e
assert not b

Note that + applied to booleans contest to integers.

AND: & and &=

assert (True & True)
assert (True and True)
assert not (True & False)
assert not (True and False)
assert not (False & True)
assert not (False and True)
assert not (False & False)
assert not (False and False)