Skip to content

Boolean Arithmetic

Boolean Arithmetic

The boolean data type is either True or False. In Python, boolean variables are defined by the keywords True and False.

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

>>> b = False
>>> type(b)
<class 'bool'>

Note that True and False must have an Upper Case first letter. Using a lowercase true returns an error.

>> c = true
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'true' is not defined
d = false
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'false' is not defined

Integers and Floats as Booleans

An int, float or complex number set to zero will always return False. An int, float or complex number set to any other number, positive or negative, will return True.

>>> zero_int = 0
>>> bool(zero_int)
False
>>> pos_int = 1
>>> bool(pos_int)
True
>>> neg_flt = -5.1
>>> bool(neg_flt)
True

Boolean arithmetic is the arithmetic of logic, the arithmetic of True and False. A boolean variable or logical value can either be True or False. The keywords not, or, and are used to modify and combine boolean values. The double equals sign == is used to test for equality. Note this is different than variable assignment which is accomplished with a single equals sign =. The symbol != tests for inequality. If two boolean values are not than, != between them will produce True.

Examples of boolean arithmetic are below:

>>> A = True
>>> B = False
>>> not A
False
>>> not B
True
>>> A == B
False
````
```python
>>> A != B
True
>>> A or B
True
>>> A and B
False

A summary of boolean arithmetic and operators is shown in the table below.

A B not A not B A == B A != B A or B A and B
T F F T F T T F
F T T F F T T F
T T F F T F T T
F F T T T F F F