π Python Comparison (Relational) Operators β Comparing Values Like a Pro
Introduction π
Comparison operators (also called relational operators) are used to compare two values. They return a Boolean result β either True or False. These operators are essential in decision-making, especially inside if statements, loops, and expressions.
Note
π‘ Understanding comparison operators is key to writing logic-driven Python programs.
1. List of Comparison Operators π
| Operator | Symbol | Meaning | Example |
|---|---|---|---|
| Equal to | == | Checks if values are equal | 5 == 5 β True |
| Not equal to | != | Checks if values are different | 5 != 3 β True |
| Greater than | > | Left value is greater | 10 > 5 β True |
| Less than | < | Left value is smaller | 3 < 7 β True |
| Greater than or equal | >= | Checks β₯ | 10 >= 10 β True |
| Less than or equal | <= | Checks β€ | 5 <= 8 β True |
2. Basic Comparison Examples π§
basic_comparisons.py
a = 10
b = 20
print(a == b) # False
print(a != b) # True
print(a > b) # False
print(a < b) # True
print(a >= 10) # True
print(b <= 15) # False3. Comparing Strings π€
Python compares strings based on alphabetical order (Unicode values).
string_compare.py
print("apple" == "apple") # True
print("apple" != "banana") # True
print("cat" > "bat") # True ('c' > 'b')
print("Zoo" < "apple") # True ('Z' < 'a')Note
β οΈ Uppercase letters come before lowercase letters.
4. Comparing Different Data Types β οΈ
Comparing incompatible types (like string and number) usually raises an error.
type_compare_error.py
# print("10" > 5) # β TypeErrorNote
π§ Always convert input values using int() or float() before comparing.
5. Comparison in Conditional Statements π§
comparison_if.py
age = int(input("Enter age: "))
if age >= 18:
print("Adult")
else:
print("Minor")6. Using Comparisons in Chains π
Python supports chained comparisons.
chained_compare.py
x = 15
print(10 < x < 20) # True
print(5 < x <= 15) # TrueNote
π‘ This is cleaner than writing: 10 < x and x < 20
7. Comparison With Boolean Values βοΈ
bool_compare.py
print(True == 1) # True
print(False == 0) # True
print(True > False) # True8. Real-World Example π
real_world_example.py
username = input("Enter username: ")
if len(username) >= 5:
print("Valid username")
else:
print("Username too short!")Conclusion π
>>βComparison operators are the heart of decision-making β they help your programs think.β π₯
You now understand all comparison (relational) operators in Python. Want the next topic? Try Logical Operators, Bitwise Operators, Conditional Statements, or Loops. Just say the word! π