3.1.1.4 Making decisions in Python
Comparison operators: greater than
You can also ask a comparison question using the
>
(greater than) operator.
If you want to know if there are more black sheep than white ones, you can write it as follows:
black_sheep > white_sheep # greater than
True
confirms it; False
denies it.Comparison operators: greater than or equal to
The greater than operator has another special, non-strict variant, but it's denoted differently than in classical arithmetic notation:
>=
(greater than or equal to).
There are two subsequent signs, not one.
Both of these operators (strict and non-strict), as well as the two others discussed in the next section, are binary operators with left-sided binding, and their priority is greater than that shown by
==
and !=
.
If we want to find out whether or not we have to wear a warm hat, we ask the following question:
centigrade_outside ≥ 0.0 # greater than or equal to
Comparison operators: less than or equal to
As you've probably already guessed, the operators used in this case are: the
<
(less than) operator and its non-strict sibling: <=
(less than or equal to).
Look at this simple example:
current_velocity_mph < 85 # less than
current_velocity_mph ≤ 85 # less than or equal to
We're going to check if there's a risk of being fined by the highway police (the first question is strict, the second isn't).
Making use of the answers
What can you do with the answer (i.e., the result of a comparison operation) you get from the computer?
There are at least two possibilities: first, you can memorize it (store it in a variable) and make use of it later. How do you do that? Well, you would use an arbitrary variable like this:
answer = number_of_lions >= number_of_lionesses
The content of the variable will tell you the answer to the question asked.
The second possibility is more convenient and far more common: you can use the answer you get to make a decision about the future of the program.
You need a special instruction for this purpose, and we'll discuss it very soon.
Now we need to update our priority table, and put all the new operators into it. It now looks as follows:
Priority | Operator | |
---|---|---|
1 | + , - | unary |
2 | ** | |
3 | * , / , // , % | |
4 | + , - | binary |
5 | < , <= , > , >= | |
6 | == , != |
Comments
Post a Comment