Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

šŸ“Š Python Relational Operators: Complete Guide

Python Relational Operators - Complete Guide

Relational operators let you compare values and make decisions in your Python code.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
šŸ“‘ On this page:
  • What are Relational Operators?
  • Quick Reference Table
  • Equal to (==)
  • Not Equal (!=)
  • Greater Than (>)
  • Less Than (<)
  • Greater Than or Equal To (>=)
  • Less Than or Equal To (<=)
  • Real-World Examples
  • Common Mistakes to Avoid
  • Try It Yourself
  • Quick Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
šŸ“š What You'll Learn Here
  • What relational operators are — tools to compare values
  • Equal to (==) — check if two values are equal
  • Not Equal (!=) — check if two values are different
  • Greater Than (>) — check if one value is larger
  • Less Than (<) — check if one value is smaller
  • Greater Than or Equal To (>=) — check if one value is larger or equal
  • Less Than or Equal To (<=) — check if one value is smaller or equal
  • Real-world examples — age verification, grading, eligibility checks
  • Common mistakes — and how to avoid them

What are Relational Operators?

Relational operators (also called comparison operators) are used to compare two values and determine the relationship between them. They always return a Boolean value: True or False.

šŸ’” Key insight: Relational operators are the foundation of decision-making in Python. They power if statements, while loops, and all conditional logic.

Think of them as the "question words" of programming. They ask questions like: "Is this equal to that?" or "Is this greater than that?" and Python answers with True or False.

Quick Reference Table

Here's a quick reference of all Python relational operators:

Operator Example Result Description
== 5 == 5 True Equal to
!= 5 != 3 True Not equal
> 5 > 3 True Greater than
< 5 < 3 False Less than
>= 5 >= 5 True Greater than or equal to
<= 5 <= 10 True Less than or equal to

1. Equal To (==)

The equal to operator (==) checks if two values are equal. It returns True if they are equal, and False otherwise.

# Equal To (==) Examples
print(5 == 5)   # Output: True
print(5 == 3)   # Output: False

# With variables
x = 10
y = 10
print(x == y)   # Output: True

# With strings
print("hello" == "hello")  # Output: True
print("hello" == "world")  # Output: False

2. Not Equal (!=)

The not equal operator (!=) checks if two values are different. It returns True if they are not equal, and False otherwise.

# Not Equal (!=) Examples
print(5 != 3)   # Output: True
print(5 != 5)   # Output: False

# With variables
a = 10
b = 20
print(a != b)   # Output: True

# With strings
print("python" != "java")  # Output: True
print("python" != "python")  # Output: False

3. Greater Than (>)

The greater than operator (>) checks if the left value is greater than the right value.

# Greater Than (>) Examples
print(5 > 3)    # Output: True
print(3 > 5)    # Output: False
print(5 > 5)    # Output: False

# With variables
age = 18
print(age > 17)  # Output: True

4. Less Than (<)

The less than operator (<) checks if the left value is less than the right value.

# Less Than (<) Examples
print(3 < 5)    # Output: True
print(5 < 3)    # Output: False
print(5 < 5)    # Output: False

# With variables
score = 75
print(score < 80)  # Output: True

5. Greater Than or Equal To (>=)

The greater than or equal to operator (>=) checks if the left value is greater than or equal to the right value.

# Greater Than or Equal To (>=) Examples
print(5 >= 5)   # Output: True
print(5 >= 3)   # Output: True
print(3 >= 5)   # Output: False

# With variables
temperature = 30
print(temperature >= 25)  # Output: True

6. Less Than or Equal To (<=)

The less than or equal to operator (<=) checks if the left value is less than or equal to the right value.

# Less Than or Equal To (<=) Examples
print(5 <= 5)   # Output: True
print(3 <= 5)   # Output: True
print(5 <= 3)   # Output: False

# With variables
discount = 10
print(discount <= 15)  # Output: True

7. Real-World Examples

šŸŽ“ Age Verification for Voting

# Age Verification Example
age = 18
voting_age = 18

if age >= voting_age:
    print("You are eligible to vote!")
else:
    print("You are not eligible to vote yet.")

# Output: You are eligible to vote!

šŸ“Š Grade Calculator

# Grade Calculator Example
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Score: {score}, Grade: {grade}")

# Output: Score: 85, Grade: B

šŸ·ļø Price Comparison for Shopping

# Price Comparison Example
price1 = 25.99
price2 = 30.50

if price1 < price2:
    print("Item 1 is cheaper!")
elif price1 > price2:
    print("Item 2 is cheaper!")
else:
    print("Both items have the same price!")

# Output: Item 1 is cheaper!

8. Common Mistakes to Avoid

āŒ Mistake 1: Using = instead of ==

This is the most common mistake! = is for assignment, == is for comparison.

# WRONG (assignment instead of comparison)
if x = 5:  # This will cause a SyntaxError!
    print("x is 5")

# CORRECT (comparison)
if x == 5:
    print("x is 5")

āŒ Mistake 2: Confusing > and <

Remember: > means "greater than" and < means "less than."

# WRONG
if 5 < 3:  # This is False, not True!
    print("This won't print")

# CORRECT
if 5 > 3:  # This is True
    print("5 is greater than 3")

āŒ Mistake 3: Comparing different data types

Python can compare numbers, but comparing strings with numbers may cause errors.

# WRONG (comparing string with number)
if "10" > 5:  # TypeError in some cases
    print("This may cause an error")

# CORRECT (convert to same type)
if int("10") > 5:  # Convert string to int
    print("10 is greater than 5")

Try It Yourself!

Experiment with relational operators directly in your browser. Modify the code and see the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
RELATIONAL OPERATORS
========================================

1. EQUAL TO (==)
5 == 5: True
5 == 3: False

2. NOT EQUAL (!=)
5 != 3: True
5 != 5: False

3. GREATER THAN (>)
5 > 3: True
3 > 5: False

4. LESS THAN (<)
3 < 5: True
5 < 3: False

5. GREATER THAN OR EQUAL TO (>=)
5 >= 5: True
5 >= 3: True

6. LESS THAN OR EQUAL TO (<=)
5 <= 5: True
3 <= 5: True

7. REAL-WORLD EXAMPLE (Age Verification)
Age: 18
Can vote? True

āœ… Relational operators help you make decisions!
šŸ†

šŸŽ‰ You've Mastered Python Relational Operators!

You understand all relational operators (==, !=, >, <, >=, <=). These are essential for decision-making in Python!

Quick Quiz – Test Your Knowledge

Let's see what you've learned about Python relational operators:

1. What is the result of 5 == 5 in Python?
2. Which operator checks if two values are NOT equal?
3. What is the result of 10 > 15?

Frequently Asked Questions

šŸ¤” What's the difference between = and ==? ā–¼

= is the assignment operator used to assign values to variables. == is the equality operator used to compare two values. Never confuse them!

šŸ”§ Can relational operators work with strings? ā–¼

Yes! Relational operators work with strings too. Python compares strings lexicographically (alphabetically). For example, "apple" < "banana" returns True.

šŸ“ What do relational operators return? ā–¼

All relational operators return a Boolean value: True or False. They are used in conditional statements and loops.

šŸ“Š Can I chain relational operators in Python? ā–¼

Yes! Python supports chaining comparisons like 5 < x < 10. This checks if x is between 5 and 10.

šŸ“š Where to Go From Here

Now that you understand Python relational operators, here are some related topics to explore:

🧠 Logical Operators

Combine conditions with AND, OR, NOT

šŸŽÆ Decision Making

Use conditions to control program flow

šŸ“ If Statements

Make decisions with if, elif, else

šŸ“– Related Tutorials
  • Logical Operators
  • Decision Making
  • if Statements
  • Arithmetic Operators
šŸ“– Interview & FAQ Resources
  • SQL - Displaying Data from Multiple Tables FAQ
  • SQL Window Functions & Analytic Functions FAQ
  • Python Data Types Interview Questions
  • Python Tuples and Sets Interview Questions
  • Java Basic Input/Output Interview Questions
  • Java Advanced Threads and Concurrency Interview Questions
Previous: Shorthand Assignment Next: Logical Operators →