πŸ” 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 πŸ“‹

OperatorSymbolMeaningExample
Equal to==Checks if values are equal5 == 5 β†’ True
Not equal to!=Checks if values are different5 != 3 β†’ True
Greater than>Left value is greater10 > 5 β†’ True
Less than<Left value is smaller3 < 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)  # False

3. 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)  # ❌ TypeError

Note

🧠 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)   # True

Note

πŸ’‘ 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) # True

8. 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! 😊