Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1

82 Chapter 5


they equal? Each comparison you make using a comparison opera-
tor is a condition that will evaluate to True or False. One real-world
example of a comparison is when you enter a passcode to access a
building. The Boolean expression takes the passcode you entered
and compares it to the correct passcode; if the input matches (is
equal to) the correct passcode, the expression evaluates to True,
and the door opens.
The comparison operators are shown in Table 5-1.

Table 5-1: Python Comparison Operators
Math
symbol

Python
operator

Meaning Example Result

< < Less than 1 < 2 True
> > Greater than 1 > 2 False
≤ <= Less than or equal to 1 <= 2 True
≥ >= Greater than or equal to 1 >= 2 False
= == Equal to 1 == 2 False
≠ != Not equal to 1 != 2 True

As we saw with math operators in Chapter 3, some of the oper-
ators in Python are different from math symbols to make them
easier to type on a standard keyboard. Less than and greater than
use the symbols we’re used to, < and >.
For less than or equal to, Python uses the less than sign and
equal sign together, <=, with no space in between. The same goes for
greater than or equal to, >=. Remember not to put a space between
the two signs, as that will cause an error in your program.
The operator to see if two values are
equal is the double equal sign, ==, because
the single equal sign is already used as the
assignment operator. The expression x = 5
assigns the value 5 to the variable x, but
x == 5 tests to see if x is equal to 5. It’s help-
ful to read the double equal sign out loud as
“is equal to” so you can avoid the common
mistake of writing the incorrect statement
if x = 5 instead of the correct if x == 5
(“if x is equal to five”) in your programs.
Free download pdf