Relational Operators in Python : Different Types & Examples

Updated on September 25, 2024

Article Outline

Relational operators are used to form a relation between two or more operands using the comparison method like greater than, less than, equal to and not equal. After the comparison of the two operands the result is a boolean value. They make it possible to compare values which makes it easier to perform vital functions like conditional execution, data filtering, validation, and effective algorithm implementation. Relational operators are essential to programming because they make software more functional and interactive by enabling the creation of complicated logical conditions.

Relational Operators in Python

List of Relational Operators in Python

 

Operator Name Description Syntax
== Equal to Here if the value of x is same as the value of y then the statement is true else it is false. x==y
!= Not equal to If the value of x does not match the value of y then the operator statement is true. x!=y
> Greater than When the value of x is larger than the value of y, we use the greater than operator. x>y
< Less than When the value of x is smaller than the value of y, we use the less than operator. x<y
>= Greater than or equal to Whenever the value of x is greater than or equal to the value of y, we use the greater than or equal to operator. x>=y
<= Less than or equal to Whenever the value of x is smaller than or equal to the value of y, we use the less than or equal to operator. x<=y
*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Practical Examples

Comparing Numbers

Relational operators are normally used to compare integers and floating-point numbers.

 

Example:

 

x = 10

y = 20

 

  • Equal to (==):

 

print(x == y)

 

  • Output:

False

 

  • Greater than (>):

 

print(x > y)

 

  • Output:

False

 

  • Less than or equal to(<=):

 

print(x <= y)

 

  • Output:

True

Comparing Strings

 

In Python, strings can be compared using relational operators. In this, we compare them on the basis of lexicographical (dictionary) order which means Python compares characters using their Unicode values.

 

Example:

 

a1 = “apple”

a2 = “banana”

 

  • Equal to(==):

 

print(a1 == a2)

 

  • Output:

False

 

  • Not equal to(!=):

 

print(a1 != a2)

 

  • Output:

True

 

  • Less than(<):

 

print(a1 < a2)

 

  • Output:

 

True (because ‘a’ comes before ‘b’)

 

  • Greater than(>):

 

print(a2 > a1)

 

  • Output:

 

True (because ‘banana’ comes after ‘apple’)

 

Comparing Lists and Other Data Structures

 

In Python, we can also compare other data structures like lists, tuples, and sets. As seen above, lists are also compared in the same way as strings that are element by element.

 

List

 

l1 = [1, 2, 3]

l2 = [1, 2, 4]

 

  • Equal to(==):

 

print(l1 == l2)

Output: False

 

  • Not equal to(!=):

 

print(l1 != l2)

Output: True

 

  • Less than(<):

 

print(l1 < l2)

Output: True (because 3 < 4 at the third position)

 

  • Greater than(>):

 

print(l2 > l1)

Output: True

 

Tuples

 

t1 = (1, 2, 3)

t2 = (1, 2, 5)

 

print(t1 < t2)

 

Output: True                                                                      #because 3 < 5

 

Sets

 

In Python, the sets and not in order therefore the greater than and less than operators do not work directly.

 

s1 = {1, 2, 3}

s2 = {1, 2, 3, 4}

 

  • Subset

print(s1 <= s2)

 

  • Output: True

 

  • Superset

print(s2 >= s1)

 

  • Output: True

 

  • Not Equal

print(s1 != s2)

 

  • Output: True

Common Use Cases

Relational Operators are used on various platforms. Let us look at some of the common use cases:

Conditional Statements

In order to run a program efficiently sometimes the relational operators are used in if, elif, and else.

 

Example:

age = 18   if age >= 18: print("Eligible.") else: print("Not eligible.")

Output:

Eligible.

Multiple Conditions

You can combine relational operators with logical operators and, or, not for more complex conditions.

 

Example:

temperature = 25 humidity = 60  if temperature > 20 and humidity < 70: print("The weather is nice.") else: print("It's not the best weather today.")

Output:

The weather is nice.

 

Loops

 

For Loop

 

In for loops, relational operators can be used with the range() function or other iterable data types.

 

Example:

for num in range(1, 6): if num % 2 == 0: print(f"{num} is even.")

Output:

2 is even. 4 is even.

While Loop

 

count = 0   while count < 5: print("Count is:", count) count += 1

Output:

0, 1, 2, 3, 4

Data Validation

Relational operators are also useful for validating user input, ensuring data is within a certain range or follows specific rules.

 

Example:

 

Check if the number is within the given range:

n = int(input("Enter any number from 1 to 100: "))  if 1 <= n <= 100: print("Valid number.") else: print("Invalid number. Please try again.")

Advanced Topics

Beyond basic comparisons, Python offers more advanced ways to use relational operators, including chaining comparisons and using them within functions. Let’s explore these topics in depth.

Chaining Relational Operators

Python allows the user to chain multiple relational operators together which helps the user to execute multiple comparisons in just one statement. This also makes the code easy to read and understand as it uses layman terms.

 

Example:

x = 10 if 5 < x < 15:   print("x is between 5 and 15.")

Output:

x is between 5 and 15. <em>In the above example, 5 < x < 15 evaluates if x is greater than 5 and less than 15 in one expression, which is equivalent to:</em>   if 5 < x and x < 15: pass

Benefits of Chaining:

 

  • Chaining is concise and easy to read, especially for range checks.
  • Python evaluates the chained comparisons left to right. It only checks the next condition if the current one is True, which can help optimize performance in some cases.

 

Also Read: While Loop in Python

Using Relational Operators with Functions

You can use relational operators within functions to make comparisons more modular and reusable. This is particularly useful when you’re comparing complex data or when the same comparison is needed in multiple parts of the code.

 

Example: Using Relational Operators to Validate Custom Functions

def inrange(number, lower, upper): return lower <= number <= upper   if inrange(7, 5, 10): print("Number is within range.")

Output:

Number is within range.

In this example, the function “inrange()” simplifies the logic of checking whether a number lies between two limits.

 

Also Read: Difference between For Loop and While Loop in Python

Conclusion

In Python, relational operators are a component of a fundamental programming idea. They are essential for drawing logical conclusions from value comparisons. When expressing relationships between variables, these operators offer a clear and comprehensible method, whether they are utilized for data analysis or in conditional statements.

 

Writing effective Python code requires an understanding of relational operators and how to combine and use them. A firm understanding of these operators will surely improve your capacity to write reliable and useful programs as you work through increasingly difficult programming assignments and a compilation of code snippets.

FAQs
Strings are compared lexicographically (alphabetically), based on Unicode values. For example, "apple" < "banana" returns True because "a" comes before "b".
Relational operators can be used inside functions for tasks like data validation or complex comparisons. Functions make comparisons reusable and modular.
They compare values and return a Boolean result.   Example:   x = 10 y = 20 print(x == y)   Output: False

Updated on September 25, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved