Lesson 3b - Booleans
Booleans are one of the simplest data types. It consists entirely of “True” and “False”.
Table of Contents
Lesson Objectives
- Learn what booleans are.
- Use boolean operators.
- Compare numerical values.
What’s a Boolean?
Named after George Boole, a boolean is a value that is either true or false. It’s most commonly used in logic. In Python, it’s useful for creating conditional statements and loops, which we’ll talk about in lesson 4.
Creating a Boolean Value
In Python, declaring a boolean value is similar to declaring a number. Rather than using a numerical constant, you need to use True
or False
.
Make sure True
and False
are capitalized!
Input
a = True
print(type(a))
Output
<class 'bool'>
Boolean Operators
Just like integers and floats, booleans have their own set of algebraic rules known as Boolean Algebra.
The three most common operations are listed in the table below.
Boolean Operator | Keyword |
---|---|
AND | and |
OR | or |
NOT | not |
AND
The AND operator results in True if both booleans are already True. Otherwise, it becomes False.
Input
a = True
b = True
c = False
print(a and b)
print(a and c)
Output
True
False
OR
The OR operator results in True if at least one boolean is True. Otherwise, it becomes False.
Input
a = True
b = True
c = False
print(a or c)
print(c or c)
Output
True
False
NOT
The NOT operator reverses the current value. True becomes False, and False becomes True.
Input
a = True
c = False
print(not a)
print(not c)
Output
False
True
Order of Logical Operations
Just like regular algebra, booleans have their own order of operations. The order is listed in the table below. Operations at the top have higher precedence.
Logical Operator | Keyword |
---|---|
Brackets | ( ) |
NOT | ! |
AND | & |
OR | | |
Numerical Comparisons
We can also compare the values of expressions to generate a boolean as well.
The six comparison operators are shown in the table below.
Comparison | Symbol |
---|---|
Less than | < |
Less than or equal | <= |
Greater than | > |
Greater than or equal | >= |
Equality | == |
Inequality | != |
Input
print(5 < 8)
print(2 < 1)
print(3 == 3.0)
Output
True
False
True
Key Points / Summary
- A boolean is a True/False value.
and
,or
, andnot
are three boolean operators.- You can compare numerical values.