Making Decisions · practice
Compare Values
In the previous lesson, you used < to ask whether one number was less than another. Python has six comparison
Every comparison is an True or False.
Six comparison operators
| Operator | Question it asks |
|---|---|
== | Are these values equal? |
!= | Are these values not equal? |
< | Is the left |
<= | Is the left value less than or equal to the right value? |
> | Is the left value greater than the right value? |
>= | Is the left value greater than or equal to the right value? |
The order of the characters in <= and >= matters. Write the less-than or greater-than sign first, followed by the equals sign.
Run all six comparisons:
Change value and run the example again. Each line asks its own question about the current value.
Assignment and equality are different
A single equals sign assigns a value:
score = 8
Read this as “8 to score.” It changes what the
Two equals signs compare values:
score == 8
Read this as “is the current value of score equal to 8?” It produces a score.
This example shows both operations:
The first line assigns. The second line compares, then assigns the comparison’s result to matches_target.
Python needs both operators because assigning a value and asking about a value are different jobs.
Boundaries matter
The difference between > and >= is important at a boundary.
The first comparison is False because 18 is not greater than 18. The second is True because “greater than or equal to” includes the boundary value itself.
The same distinction applies to < and <=. Before choosing an operator, say the rule in words. If the rule says “at least 18,” use >= 18. If it says “younger than 18,” use < 18.
Strings can be equal too
Use == and != to compare
These strings are not equal because uppercase M and lowercase m are different characters. You already know how to use .strip() and .lower() when a program should ignore surrounding spaces or capitalization. We will apply that skill when user input returns later in the chapter.
Which line asks whether tickets currently contains the value 12?
What does this code print?
stock = 5
print(stock <= 5)Store the answer when you need it
A clear Boolean variable can make a later decision easier to read:
The variable name has_space describes the question answered by the comparison. In the exercise, you will create several names like this from fixed data. The next lesson will use those Boolean results to decide whether instructions should run.
Task
Create four
Set
has_spaceby comparingregisteredwithcapacity.Set
old_enoughby checking whethervisitor_ageis at leastminimum_age.Set
name_matchesby comparingentered_namewithevent_namefor equality.Set
at_capacityby checking whetherregisteredequalscapacity.
Keep the supplied data and four print calls unchanged. Submit when the summary reports the correct Boolean result on every line.