Comparison Operators in Python: Types, Syntax, Examples, and Best Practices
By Sriram
Updated on Jul 15, 2026 | 10 min read | 6.92K+ views
Share:
All courses
Certifications
More
By Sriram
Updated on Jul 15, 2026 | 10 min read | 6.92K+ views
Share:
Key Takeaways
This blog explains what comparison operators are in Python, their types, syntax, and how to use comparison operators in Python with practical examples. You'll also learn common mistakes and comparisons with different data types.
Mastering Python concepts like comparison operators lays the groundwork for machine learning. Explore upGrad's Machine Learning courses and take the next step toward building predictive models and AI-powered applications.
Popular AI Programs
Imagine writing a program that checks whether a student passed an exam or verifies if a user entered the correct password. The program has to compare values before making a decision. That's where comparison operators in Python come into play.
Simply put, comparison operators compare two values or expressions and return a Boolean value. The result is always either True or False. Python then uses that result to decide which block of code should run.
Simple example :
age = 20
print(age >= 18)
Output
True
Since 20 is greater than or equal to 18, Python returns True.
Every comparison follows the same idea. Python evaluates both sides of the operator and checks whether the condition is satisfied.
Common situations include:
Without comparison operators, Python couldn't make logical decisions.
Before writing conditions in Python, it's helpful to understand what happens behind the scenes. Every comparison follows a simple evaluation process that determines whether a condition is true or false.
The process is straightforward.
A tiny comparison can completely change how your program behaves. That's why learning this topic early makes writing conditions much easier later.
Understanding Boolean values is essential because every decision in a Python program depends on them. Whenever you compare two values, Python evaluates the condition and returns either True or False.
Expression |
Result |
| 5 > 2 | True |
| 7 == 9 | False |
| 10 <= 10 | True |
| "cat" == "dog" | False |
These Boolean results power many Python features.
Example for Boolean values :
temperature = 32
if temperature > 30:
print("It's hot today.")
The condition evaluates to True, so Python executes the print statement
Also Read: Top 36+ Python Projects for Beginners and Students to Explore in 2025
Python provides six primary comparison operators. Each one checks a different relationship between two values. Once you understand what each operator does, reading and writing conditional statements becomes much easier.
The table below gives you a quick overview.
Operator |
Meaning |
Example |
Output |
| == | Equal to | 8 == 8 | True |
| != | Not equal to | 8 != 5 | True |
| > | Greater than | 15 > 9 | True |
| < | Less than | 4 < 7 | True |
| >= | Greater than or equal to | 12 >= 12 | True |
| <= | Less than or equal to | 6 <= 8 | True |
Let's look at each one individually.
Among all comparison operators in Python, the equality operator (==) is used most frequently. It checks whether two values are exactly the same and returns either True or False, making it essential for conditions, validation, and decision-making in Python programs.
The equality operator checks whether two values are exactly the same.
username = "Alex"
print(username == "Alex")
Output
True
This operator is widely used in login systems, quizzes, and user validation.
The not equal operator (!=) is another essential comparison operator in Python. It checks whether two values are different and returns True when they don't match.
The not equal operator returns True when two values are different.
score = 75
print(score != 100)
Output
True
It's useful when your program needs to continue until a value changes or reject invalid input.
The greater than operator (>) is one of the most commonly used comparison operators in Python. It checks whether the value on the left is greater than the value on the right and returns True if the condition is satisfied, otherwise False.
salary = 65000
print(salary > 50000)
Output
True
You'll commonly see this in salary filters, age verification, and score comparisons.
The less than operator (<) is another important comparison operator in Python. It checks whether the value on the left is smaller than the value on the right and returns True when the condition is satisfied, otherwise False.
temperature = 18
print(temperature < 20)
Output
True
Programs often use this to monitor thresholds, minimum values, or warning conditions.
The greater than or equal to operator (>=) is an important comparison operator in Python when a value can either exceed or exactly match a limit. It returns True if the left value is greater than or equal to the right value.
attendance = 75
print(attendance >= 75)
Output
True
This operator is common in eligibility checks.
The less than or equal to operator (<=) is a useful comparison operator in Python when a value can be either below or exactly equal to a specified limit. It returns True if the left value is less than or equal to the right value; otherwise, it returns False.
speed = 60
print(speed <= 60)
Output
True
Developers often use it when checking limits or maximum allowed values.
Each comparison operator in Python is designed to answer a specific question. Selecting the correct operator makes your conditions more accurate, improves code readability, and helps prevent logical errors in your programs.
If you want to check... |
Use |
| Are both values equal? | == |
| Are they different? | != |
| Is one value larger? | > |
| Is one value smaller? | < |
| Is it equal to or greater? | >= |
| Is it equal to or smaller? | <= |
Learning these six operators is the first step toward writing meaningful conditions in Python. Once you're comfortable with them, you'll find it much easier to build programs that react to user input, validate information, and automate decisions.
Must read : String Comparison in Python: Operators, Methods, and Examples
Machine Learning Courses to upskill
Explore Machine Learning Courses for Career Progression
Understanding the comparison operators in Python syntax is just as important as knowing what each operator does. A small syntax mistake can change the result of your program or even stop it from running.
Python keeps comparison syntax simple. Every comparison follows the same pattern.
syntax : value1 operator value2
Python evaluates the expression from left to right and returns either True or False.
Example
x = 15
y = 20
print(x < y)
Output
True
Since 15 is less than 20, the condition evaluates to True.
The comparison itself doesn't modify either variable. It simply checks the relationship between them and returns a Boolean value.
The table below shows how each comparison operator is written.
Syntax |
Meaning |
Example |
Output |
| a == b | Equal to | 5 == 5 | True |
| a != b | Not equal to | 8 != 3 | True |
| a > b | Greater than | 15 > 12 | True |
| a < b | Less than | 7 < 10 | True |
| a >= b | Greater than or equal to | 25 >= 25 | True |
| a <= b | Less than or equal to | 9 <= 12 | True |
Every expression produces one Boolean value.
Let's look at another example.
marks = 82
print(marks >= 40)
Python follows these steps:
That Boolean value becomes extremely useful when writing conditions.
Comparison operators rarely compare fixed values in real programs.
More often, they compare variables.
price = 799
budget = 1000
print(price <= budget)
Output
True
This kind of comparison appears in shopping carts, expense trackers, and inventory systems.
Python can compare expressions instead of direct values.
a = 10
b = 15
print(a + 5 == b)
Output
True
Python first evaluates a + 5.
Then it compares the result with b.
This makes your code shorter and easier to read.
Every comparison returns either True or False.
Expression |
Result |
| 18 > 21 | False |
| 100 == 100 | True |
| "apple"!= "orange" | True |
| 12 <= 8 | False |
Boolean values drive decision-making, loops, and user input validation in Python. Learning comparison operators in Python syntax helps you write accurate conditions, especially when you understand how Python evaluates each comparison instead of simply memorizing the operators.
Also read : Precedence of Operators in Python: Complete Guide with Examples
Writing a comparison is only half the story. The real power of comparison operators in Python using if statement comes from making decisions based on the result.
Whenever an if statement runs, Python checks whether the condition is True or False. If the condition is True, the code inside the block executes. If it's False, Python skips that block and moves to the next statement.
Syntax
if condition:
# code to execute
The condition is usually a comparison expression.
Example
age = 21
if age >= 18:
print("Eligible to vote")
Output
Eligible to vote
Python evaluates age >= 18.
Since the condition is True, the message is printed.
Also Read: Understanding Python Data Types
Sometimes you want your program to perform a different action when the condition isn't met.
balance = 3500
if balance >= 5000:
print("Withdrawal approved")
else:
print("Insufficient balance")
Output
Insufficient balance
This simple pattern appears in banking apps, shopping websites, and login systems.
Some programs need to evaluate more than one condition.
marks = 76
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Grade D")
Output
Grade B
Python checks each comparison one after another until it finds a condition that evaluates to True.
Once it does, the remaining conditions are ignored.
You can even place one if statement inside another.
age = 24
has_license = True
if age >= 18:
if has_license:
print("You can drive.")
Output
You can drive.
Nested conditions are useful when one decision depends on another.Understanding this flow makes debugging much easier.
Comparison operators control decisions in almost every application.
Situation |
Comparison |
| ATM withdrawal | balance >= amount |
| Student pass or fail | marks >= 35 |
| Login system | password == saved_password |
| Voting eligibility | age >= 18 |
| Product availability | stock > 0 |
These examples show how to use comparison operator in Python beyond simple classroom exercises. Every time a program needs to make a choice, comparison operators are involved.
Also Read: Step-by-Step Guide to Learning Python for Data Science
Writing multiple comparisons doesn't always require logical operators. Python offers a cleaner way to compare several values at once through chained comparison operators in Python.
Instead of writing two separate comparisons joined by and, you can combine them into one readable expression.
Syntax
The syntax follows a natural pattern.
lower_limit <= value <= upper_limit
Example
age = 25
print(18 <= age <= 60)
Output
True
Python checks both comparisons together. Internally, it treats the expression like this.
18 <= age and age <= 60
The shorter version is easier to read and less repetitive. This style appears frequently when checking ranges.
They improve readability. They reduce repeated variable names.They closely match how people describe conditions in everyday language.
Instead of writing: if marks >= 40 and marks <= 100:
You can simply write: if 40 <= marks <= 100:
Chained comparisons work well in many situations.
Scenario |
Example |
| Age validation | 18 <= age <= 60 |
| Exam scores | 35 <= marks <= 100 |
| Working hours | 9 <= hour <= 18 |
| Product ratings | 1 <= rating <= 5 |
| Percentage checks | 0 <= percentage <= 100 |
Also read : What are Assignment Operators in Python?
Subscribe to upGrad's Newsletter
Join thousands of learners who receive useful tips
Many beginners confuse comparison and logical operators in Python because they often appear in the same statement. They work together, but they don't perform the same job. A comparison operator compares values. A logical operator combines multiple conditions. That's the key difference.
Feature |
Comparison Operators |
Logical Operators |
| Purpose | Compare two values or expressions | Combine two or more comparison expressions |
| Output | Returns True or False | Returns True or False based on the combined conditions |
| Works With | A single condition | Multiple conditions |
| Common Operators | ==, !=, >, <, >=, <= | and, or, not |
| Example Code | age = 20print(age >= 18) | age = 22citizen = Trueprint(age >= 18 and citizen) |
| Example Output | True | True |
| Use Case | Check whether one condition is true or false | Evaluate multiple conditions together before making a decision |
Ready to take your Python skills beyond the basics? As AI and machine learning continue to evolve, build a strong foundation with upGrad's Ex. Diploma in Machine Learning & AI with MLOps, Gen AI & Agentic AI to gain practical, job-ready AI skills.
Both comparison operators and identity operators use symbols that look similar, yet they answer completely different questions.
Comparison operators check whether two values are equal.Identity operators check whether two variables refer to the same object in memory.
Feature |
Comparison Operators (==) |
Identity Operators (is) |
| Purpose | Compare whether two values are equal | Check whether two variables refer to the same object in memory |
| What It Checks | Value equality | Object identity (memory reference) |
| Common Operator | == | is |
| Example Output | True | False |
| Reason | Both lists contain the same values | The lists are stored as separate objects in memory |
| When to Use | Compare data or values | Check if two variables reference the exact same object |
Use comparison operators when checking values.
Examples include:
Use identity operators only to check whether two variables reference the same object. For most beginner programs, comparison operators are the better choice. Knowing the difference helps you write accurate code and avoid common mistakes.
Reading definitions is useful. Writing code is where everything starts to make sense.
The easiest way to understand comparison operators in Python with examples is to see how they behave with different types of data. Each example below reflects situations you'll encounter while building Python programs.
You'll rarely compare fixed values in real programs. Instead, comparison operators in Python are commonly used to compare variables whose values change during execution, helping your program make decisions dynamically.
x = 45
y = 60
print(x < y)
Output
True
Python compares the values stored inside the variables, not the variable names themselves.
One of the most common uses of comparison operators with numbers in Python is checking numerical conditions.
Suppose you're building a student grading system.
marks = 72
print(marks >= 35)
Output
True
Comparison operators also work with decimal numbers.
temperature = 27.5
print(temperature < 30)
Output
True
Whether you're working with integers or floating-point values, Python evaluates them using the same comparison rules.
Many beginners are surprised to learn that comparison operators with strings in Python work without any extra functions.
Python compares strings alphabetically using Unicode values.
print("Apple" == "Apple")
Output
True
Now compare two different strings.
print("Apple" < "Banana")
Output
True
Since "Apple" comes before "Banana" alphabetically, Python returns True.
print("Python" == "python")
Output
False
Uppercase and lowercase letters have different Unicode values.
Boolean values can also be compared directly.
is_logged_in = True
is_admin = False
print(is_logged_in == is_admin)
Output
False
Comparison operators appear in many everyday programming tasks.
Scenario |
Example |
| Login validation | password == saved_password |
| Exam result | marks >= 40 |
| Age verification | age >= 18 |
| Shopping discount | cart_total > 5000 |
| Bank balance check | balance >= withdrawal |
| Stock availability | stock > 0 |
These examples show that how to use comparison operator in Python isn't limited to classroom exercises. You'll use them whenever your program needs to make a decision based on values.
Also read : Arithmetic Operators in Python
Even experienced programmers make mistakes while writing conditions. A tiny error in a comparison can change the entire program's behavior. The good news is that most of these issues are easy to avoid once you know what to look for.
Let's look at the mistakes beginners make most often when working with common mistakes with comparison operators in Python.
Mistake |
Incorrect Example |
Correct Approach |
| Using = instead of == | if age = 18: | Use == for comparisons.if age == 18: |
| Confusing == and is | x is y (when comparing values) | Use == to compare values and is only to check object identity. |
| Ignoring case when comparing strings | "Python" == "python" | Convert both strings to the same case using .lower() or .upper() before comparing. |
| Comparing incompatible data types | 20 > "18" | Convert values to the same data type before comparison. |
| Comparing floating-point numbers directly | 0.1 + 0.2 == 0.3 | Compare floating-point values within a small tolerance instead of using direct equality. |
Avoiding these mistakes will make your programs easier to debug and more reliable.
Must read: Precedence of Operators in Python
Writing conditions isn't just about getting the correct output. Using comparison operators in Python the right way makes your code easier to read, debug, and maintain as your programs become more complex.
1. Write Readable Conditions
Keep conditions simple.Instead of writing several unnecessary comparisons, focus on the one that answers your question.
Example:
if age >= 18:
This is much easier to understand than a complicated expression.
2. Use Chained Comparisons Where Appropriate
Python supports readable range checks.
Instead of writing:
if marks >= 40 and marks <= 100:
Write:
if 40 <= marks <= 100:
It looks cleaner and avoids repeating variables.
3. Compare Compatible Data Types
Before comparing values, make sure they belong to compatible data types.
For example:
age = int(input("Enter your age: "))
Now comparisons will work correctly.
4. Keep Conditions Focused
Avoid combining too many comparisons in one statement.Complex conditions are difficult to understand and debug.
Break them into smaller steps when needed.
Must read : Types of Operators in Python: A Beginner’s Guide
Learning comparison operators in Python is one of the first steps toward writing programs that make decisions. From checking user input to validating conditions and controlling program flow, these operators appear throughout Python development.
As you continue practising, focus on writing clear comparison expressions, choosing the correct operator, and testing your conditions with different inputs. A strong understanding of comparison operators makes it much easier to work with loops, functions, data structures, and more advanced Python concepts.
Ready to start your journey? Book a free consultation with upGrad today to find the best path for your career.
Yes, but you should convert the input to the correct data type first. The input() function returns a string by default, so comparing it directly with a number can produce incorrect results or errors. Converting the input using functions like int() or float() makes comparisons accurate and reliable.
Yes. Every comparison expression in Python evaluates to a Boolean value. This Boolean result determines whether a condition is satisfied and is used by statements like if, while, and conditional expressions to control the program's execution.
Absolutely. You can combine multiple comparison expressions using logical operators like and, or, and not, or write chained comparisons such as 10 <= score <= 100. Choosing the right approach makes conditions easier to understand and reduces unnecessary repetition.
The displayed values may appear identical, but differences in data type, letter case, whitespace, or floating-point precision can affect the outcome. Before comparing values, verify that they share the same format and type to avoid unexpected results.
Yes. Comparison operators help filter datasets, validate records, identify outliers, and apply conditions before training machine learning models. They are also widely used when cleaning data and selecting rows that meet specific criteria during data preprocessing.
Yes. Python allows you to compare date and time objects to determine whether one occurs before, after, or at the same time as another. This is useful for scheduling applications, event tracking, reminders, and time-based data analysis.
Empty strings, empty lists, and None represent different kinds of values in Python. While empty collections can be compared, None should typically be checked using identity operators. Understanding these differences helps prevent logic errors in conditional statements.
Use chained comparisons when checking whether a value falls within a range. They make the code shorter and more readable than repeating the same variable with multiple conditions. They're especially useful for validating scores, ages, percentages, and other numeric limits.
Try your program with different input values, including edge cases such as zero, negative numbers, equal values, and empty strings. Testing a variety of scenarios helps confirm that your comparison conditions behave as expected in real situations.
After understanding comparison operators, focus on logical operators, conditional statements, loops, functions, and exception handling. These concepts build on comparison logic and allow you to write more interactive and practical Python applications.
Practice is the fastest way to build confidence. Start by solving small coding problems that involve conditions, such as checking age limits, validating passwords, or comparing prices. As you work on real examples, choosing the correct comparison operator becomes much more intuitive.
631 articles published
Sriram K is a Senior SEO Executive with a B.Tech in Information Technology from Dr. M.G.R. Educational and Research Institute, Chennai. With over a decade of experience in digital marketing, he specia...
Speak with AI & ML expert
By submitting, I accept the T&C and
Privacy Policy
Top Resources