boolean expressions

You learned before that we can use arithmetic operators to create expressions that evaluate to numbers. For example, + is an arithmetic operator, and 3 + 4 evaluates to 7. You can use comparison operators to create expressions that evaluate to booleans:

print(4 < 5)
True

< is a comparison operator, and 4 < 5 is an expression that evaluates to True.

There are several other comparison operators:

print(4 < 5)
print(10 > 11)
print(7 == 7)
print(14 >= 5)
print(9 <= 9)
print(1 != 6)
print(1 != 1)
True
False
True
True
True
True
False

Note that we wrote 7 == 7 instead of 7 = 7. That’s because we use a single = for assigning values to variables, as in foo = 7. We call it the assignment operator. The double == is a comparison operator. It compares two things and checks if they’re equal.

The last operator, != means “not equal.” It’s the opposite of ==.

You can store the results of boolean expressions in variables:

foo = 5 < 3
print(foo)
bar = 14 == 14
print(bar)
False
True

Just as the computer evaluates arithmetic expressions, it will evaluate boolean expressions. Consider the following block:

a = 3
b = 2 > 4
c = a == 3

This will get evaluated like so:

    a = 3
    b = 2 > 4
 -> b = False
    c = a == 3
 -> c = 3 == 3
 -> c = True

In English, the third line means that c will be True if the value of a is 3, otherwise c will be False.


previous: booleans next: if