Hello, Stellar Navigator! Today, we're diving into Python Comparison Operators. These operators allow us to compare two values, yielding a boolean
result — True
or False
. Our goal is to understand these operators and become comfortable with operator chaining. Are you ready? Let's delve in!
Comparison operators in Python are used to compare two values and yield a boolean
outcome. The comparison operators in Python are:
- Equal to (
==
)- Note that
=
and==
are two different operators - the former is an assignment operator (e.g.,variable = 2
), and the latter is the equality comparison.
- Note that
- Not equal to (
!=
) - Greater than (
>
) - Less than (
<
) - Greater than or equal to (
>=
) - Less than or equal to (
<=
)
For instance, if you have $20
and want to buy a $15
toy, see the example below:
Here, we use the >=
comparison operator to check if we have enough money to buy the toy — the answer is True
! Note how we assigned the result of the comparison to a new variable - can_buy_toy.
Let's investigate these operators further with some coding examples:
The result of these comparison operators is a boolean
value — True
or False
.
Python allows us to chain together comparisons. This technique can be handy when we want to perform multiple comparisons in a single line:
In this case, we've used operator chaining to verify whether a book that's 150 pages long falls within the range of 100 to 200 pages. The answer is True
!
Let's apply comparison operators to numbers and strings:
In Python, strings are compared alphabetically. To provide a real-life example - imagine both words in the word dictionary, which one will go first there? This word is less than the other one!
Congratulations! Today, we navigated through the Python comparison operators and the concept of operator chaining. We saw them in action with some practical examples. Our upcoming exercises provide numerous opportunities for you to practice these concepts. Remember, each correct solution brings you closer to mastering Python. Happy coding!
