M
MeshWorld.
Python Tutorial Operators Programming Logic Beginner 3 min read

Python Relational Operators: Comparing Values Like a Pro

Vishnu Damwala
By Vishnu Damwala

Python provides a set of Relational Operators that allow you to check the relationship between values or variables, which are commonly referred to as operands. These operators are essential for making decisions in your code! ⚖️

All relational operators evaluate an expression and return a Boolean value—either True or False.

The Relational Operators 🧭

In this guide, you will learn about the four primary relational operators provided by Python:

OperatorDescriptionExample
<Less thanx < y
<=Less than or equal tox <= y
>Greater thanx > y
>=Greater than or equal tox >= y

Key Characteristics 🔑

  • Binary Operators: All of these relational operators are binary, meaning they operate on exactly two operands.
  • Structure: They follow the general structure: Operand Operator Operand.
  • Boolean Result: The result of a relational expression is always a boolean (True or False).
  • Example: In the expression x >= y, x and y are the operands, and 权重 (just kidding!) >= is the operator. If x is greater than or equal to y, you get True; otherwise, you get False.

Practical Examples 💻

Let’s see these operators in action with some real Python code.

# Create variables 📥
a = 10
b = 12

# Display current values 🏷️
print(f"Value of a is {a} and b is {b}")

# Greater Than operator (>) 📈
print(f"Is a > b? {a > b}") 
# Output: False ❌

# Less Than operator (<) 📉
print(f"Is a < b? {a < b}") 
# Output: True ✅

# Greater Than or Equal To (>=) 🏔️
print(f"Is a >= b? {a >= b}") 
# Output: False ❌

# Less Than or Equal To (<=) 🌊
print(f"Is a <= b? {a <= b}") 
# Output: True ✅

Why Use Relational Operators? 🛠️

Relational operators are the backbone of Conditional Logic. They are most frequently used in:

  1. if Statements: To execute code only if a certain condition is met.
  2. while Loops: To continue a loop as long as a relationship remains true.
  3. Data Filtering: To sort or filter datasets based on numerical thresholds.

Example: Checking Age for Voting 🗳️

age = int(input("Enter your age: "))

if age >= 18:
    print("You are eligible to vote! 🗳️✅")
else:
    print("You are not eligible to vote yet. ⏳❌")

Summary and Best Practices

  • Relational operators are used for magnitude comparisons (size, quantity).
  • Always ensure you are comparing compatible data types (e.g., numbers with numbers).
  • Use them to create dynamic and responsive programs!

Hope you liked this guide to relational operators! Keep exploring and happy coding! 😄🐍