Operators: Comparison Operators (==, !=, <, >, <=, >=)
Following our exploration of Operators: Arithmetic Operators, this article dives into the world of comparison operators in Python. These operators allow you to compare two values and get a boolean result (True or False).
📚 Prerequisites
A basic understanding of Python variables and data types.
🎯 Article Outline: What You'll Master
In this article, you will learn:
- ✅ The six comparison operators in Python.
- ✅ How to compare numbers and strings.
- ✅ The difference between
==andis.
🧠 Section 1: The Comparison Operators
Python has six comparison operators:
| Operator | Name | Example |
|---|---|---|
== | Equal to | 10 == 5 |
!= | Not equal to | 10 != 5 |
< | Less than | 10 < 5 |
> | Greater than | 10 > 5 |
<= | Less than or equal to | 10 <= 5 |
>= | Greater than or equal to | 10 >= 5 |
These operators will always return a boolean value: True or False.
💻 Section 2: Comparing Numbers and Strings
Comparison operators can be used to compare numbers and strings.
Comparing Numbers:
print(10 > 5) # Output: True
print(10 == 10.0) # Output: True
Comparing Strings:
When comparing strings, Python uses lexicographical (alphabetical) order.
print("apple" < "banana") # Output: True
print("hello" == "world") # Output: False
🛠️ Section 3: == vs. is
It's important to understand the difference between the == and is operators.
==(Equality): Checks if the values of two operands are equal.is(Identity): Checks if two variables point to the same object in memory.
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
print(list1 == list2) # Output: True (the values are the same)
print(list1 is list2) # Output: False (they are two different objects)
print(list1 is list3) # Output: True (they point to the same object)
For comparing with None, you should always use is.
💡 Conclusion & Key Takeaways
You've now learned how to use comparison operators to compare values in Python.
Let's summarize the key takeaways:
- Comparison Operators:
==,!=,<,>,<=,>=. - Boolean Result: Comparison operators always return
TrueorFalse. ==vs.is:==checks for equality of value, whileischecks for identity of object.
Challenge Yourself: Write a script that takes two numbers as input and prints which one is larger.
➡️ Next Steps
In the next article, we'll learn about "Operators: Logical Operators (and, or, not)".
Happy coding!
Glossary (Python Terms)
- Comparison Operator: An operator that compares two values and returns a boolean result.
- Lexicographical Order: Alphabetical order.
- Identity: Whether two variables refer to the same object in memory.