StudyLover
  • Home
  • Study Zone
  • Profiles
  • Typing Tutor
  • Contact us
  • Sign in
StudyLover Comparison (Relational) Operators
Download
  1. Python
  2. Pyhton MCA (Machine Learning using Python)
  3. Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP
Arithmetic Operators : Logical Operators
Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP

== (Equal to)

In Python, the == (Equal to) operator is used in two main ways: for value equality and for powerful, custom logic in your own classes through operator overloading.

You can significantly increase the power of your code by defining what "equality" means for your own objects, which allows for more intuitive and readable comparisons.


1. Value Equality

This is the most common use of the == operator. It compares two objects and returns True if they have the same value, and False otherwise. This works for all built-in data types like numbers, strings, lists, and dictionaries.

Python

# --- Value Equality ---

print(f"Is 10 == 10? {10 == 10}")

# Output: True

 

print(f"Is 'hello' == 'world'? {'hello' == 'world'}")

# Output: False

 

list_a = [1, 2, 3]

list_b = [1, 2, 3]

print(f"Is list_a == list_b? {list_a == list_b}")

# Output: True (because their contents are the same)


2. Increasing Power with Operator Overloading (__eq__)

You can define the behavior of the == operator for your own custom classes by implementing the __eq__ special method. This allows you to define what it means for two instances of your class to be considered "equal."

Example: Comparing Recipe Objects

Let's extend the Recipe class from your Canvas. By default, two Recipe objects are only considered equal if they are the exact same object in memory. However, we might want to consider two recipes equal if they have the same name and ingredients, even if they are different objects. We can achieve this with __eq__.

Python

class Recipe:

    """A class to represent a recipe with ingredients and servings."""

    def __init__(self, name, servings, ingredients):

        self.name = name

        self.servings = servings

        self.ingredients = ingredients

 

    def __repr__(self):

        return (f"Recipe(name='{self.name}', servings={self.servings}, "

                f"ingredients={self.ingredients})")

 

    def __eq__(self, other):

        """

        This is the special method that defines the behavior of the '==' operator.

        It checks if two Recipe objects are equal based on their name and ingredients.

        """

        if not isinstance(other, Recipe):

            return NotImplemented

 

        # We consider two recipes equal if their names and ingredients are the same.

        return self.name == other.name and self.ingredients == other.ingredients

 

# --- Create Instances of the Class ---

recipe1 = Recipe("Spicy Curry", 4, {"chicken_grams": 500, "chili_powder_tsp": 2})

recipe2 = Recipe("Spicy Curry", 4, {"chicken_grams": 500, "chili_powder_tsp": 2})

recipe3 = Recipe("Mild Curry", 4, {"chicken_grams": 500, "chili_powder_tsp": 0.5})

 

print("--- Comparing Custom Objects ---")

# Because we defined __eq__, this now compares the content of the objects.

print(f"Is recipe1 == recipe2? {recipe1 == recipe2}")

# Output: True

 

print(f"Is recipe1 == recipe3? {recipe1 == recipe3}")

# Output: False

By implementing __eq__, you make your code more intuitive. The line recipe1 == recipe2 now has a meaningful, domain-specific logic, which is far more powerful than having to write a separate function like are_recipes_equal(recipe1, recipe2).

!= (Not equal to)

In Python, the != (Not Equal To) operator is primarily used for value inequality, but its power can be significantly enhanced for your custom classes through operator overloading.


1. Value Inequality

This is the standard and most common use of the != operator. It compares two objects and returns True if their values are not the same, and False if they are. This works intuitively for all of Python's built-in data types.

Python

# --- Value Inequality Examples ---

 

# For numbers

print(f"Is 10 != 5? {10 != 5}")

# Output: True

 

# For strings

print(f"Is 'hello' != 'hello'? {'hello' != 'hello'}")

# Output: False

 

# For lists

list_a = [1, 2, 3]

list_b = [1, 2, 4]

print(f"Is list_a != list_b? {list_a != list_b}")

# Output: True (because their contents are different)


2. Increasing Power with Operator Overloading (__ne__)

You can define the behavior of the != operator for your own custom classes, like the Recipe class in your Canvas, by implementing the __ne__ special method. This allows you to define what it means for two instances of your class to be considered "not equal."

While you can implement __ne__ directly, Python is smart. If you have already implemented the __eq__ (equal to) method, Python will automatically use its opposite for the != operator. However, for clarity and completeness, you can define it explicitly.

Example: Comparing Recipe Objects

Let's add the __ne__ method to the Recipe class from your Canvas. We can define two recipes as "not equal" if their names or ingredients are different.

Python

class Recipe:

    """

    A class to represent a recipe with ingredients, servings, and ingredient types.

    """

    def __init__(self, name, servings, ingredients):

        self.name = name

        self.servings = servings

        self.ingredients = ingredients

 

    def __repr__(self):

        return (f"Recipe(name='{self.name}', servings={self.servings}, "

                f"ingredients={self.ingredients})")

 

    def __eq__(self, other):

        """Defines the behavior of the '==' operator."""

        if not isinstance(other, Recipe):

            return NotImplemented

        return self.name == other.name and self.ingredients == other.ingredients

 

    def __ne__(self, other):

        """

        This is the special method that defines the behavior of the '!=' operator.

        It checks if two Recipe objects are not equal.

        """

        # We can simply return the opposite of the __eq__ method's result.

        return not self.__eq__(other)

 

# --- Create Instances of the Class ---

recipe1 = Recipe("Spicy Curry", 4, {"chicken_grams": 500, "chili_powder_tsp": 2})

recipe2 = Recipe("Spicy Curry", 4, {"chicken_grams": 500, "chili_powder_tsp": 2})

recipe3 = Recipe("Mild Curry", 4, {"chicken_grams": 500, "chili_powder_tsp": 0.5})

 

print("--- Comparing Custom Objects ---")

# Because we defined __ne__, this now has custom logic.

print(f"Is recipe1 != recipe2? {recipe1 != recipe2}")

# Output: False (because their names and ingredients are the same)

 

print(f"Is recipe1 != recipe3? {recipe1 != recipe3}")

# Output: True (because their names are different)

By implementing __ne__, you make your code more intuitive and readable. The expression recipe1 != recipe3 is a clear and powerful way to check for inequality based on the specific rules you've defined for your class.

 

> (Greater than)

In Python, the > (Greater Than) operator is used in two main ways: for value comparison between built-in types and for creating powerful, custom logic for your own classes through operator overloading.

You can increase the power of your code by defining what "greater than" means for your own objects, allowing you to write comparisons that are both intuitive and highly readable.


1. Value Comparison

This is the standard use of the > operator. It compares two objects and returns True if the left operand is greater than the right operand, and False otherwise.

  • For Numbers: It performs a standard mathematical comparison.

Python

print(f"Is 20 > 10? {20 > 10}")

# Output: True

  • For Sequences (Strings, Lists, Tuples): It performs a lexicographical comparison. This means it compares the items of the sequences one by one from the beginning. The first difference it finds determines the result. It's similar to how words are ordered in a dictionary.

Python

print(f"Is 'apple' > 'banana'? {'apple' > 'banana'}")

# Output: False (because 'a' comes before 'b')

 

print(f"Is [1, 5] > [1, 2, 9]? {[1, 5] > [1, 2, 9]}")

# Output: True (it compares the first elements which are equal (1), then compares the second elements (5 > 2) and stops)


2. Increasing Power with Operator Overloading (__gt__)

You can define the behavior of the > operator for your own custom classes by implementing the __gt__ special method. This allows you to define a meaningful "greater than" relationship that is specific to your class's logic.

Example: Comparing Recipe Objects

Let's extend the Recipe class from your Canvas. It's intuitive to say that one recipe is "greater than" another if it produces more servings. We can implement this logic using __gt__.

# --- 1. Define the Custom Class ---

class Recipe:

    """A class to represent a recipe with ingredients and servings."""

 

    def __init__(self, name, servings, ingredients):

        """

        The constructor for the class.

        """

        self.name = name

        self.servings = servings

        self.ingredients = ingredients

 

    def __repr__(self):

        """

        Provides a developer-friendly string representation of the object.

        """

        return (f"Recipe(name='{self.name}', servings={self.servings})")

 

    def __gt__(self, other):

        """

        This is the special method that defines the behavior of the '>' operator.

        It compares two Recipe objects based on their number of servings.

        """

        # Ensure we are comparing with another Recipe object.

        if not isinstance(other, Recipe):

            return NotImplemented

 

        # Return True if this recipe's servings are greater than the other's.

        return self.servings > other.servings

 

# --- 2. Create Instances of the Class ---

# Create two recipe objects with different serving sizes.

large_cake_recipe = Recipe(

    name="Large Party Cake",

    servings=16,

    ingredients={"flour_grams": 400, "sugar_grams": 300, "eggs": 8}

)

 

small_cake_recipe = Recipe(

    name="Small Snack Cake",

    servings=8,

    ingredients={"flour_grams": 200, "sugar_grams": 150, "eggs": 4}

)

 

print("--- Original Recipes ---")

print(large_cake_recipe)

print(small_cake_recipe)

 

# --- 3. Use the '>' Operator on Custom Objects ---

# Because we defined the __gt__ method, we can now use the '>' operator

# to compare our two Recipe objects in an intuitive way.

if large_cake_recipe > small_cake_recipe:

    print(f"\nThe '{large_cake_recipe.name}' serves more people than the '{small_cake_recipe.name}'.")

else:

    print(f"\nThe '{small_cake_recipe.name}' serves more people than the '{large_cake_recipe.name}'.")

 

# You can also use it directly in boolean expressions.

is_larger = large_cake_recipe > small_cake_recipe

print(f"Is the large cake recipe greater than the small one? {is_larger}")

 

 

< (Less than)

In Python, the < (Less than) operator is used in two main ways: for value comparison between built-in types and for creating powerful, custom logic for your own classes through operator overloading.

You can increase the power of your code by defining what "less than" means for your own objects, which allows for more intuitive and readable comparisons, similar to the __gt__ method in your Canvas code.


1. Value Comparison

This is the standard use of the < operator. It compares two objects and returns True if the left operand is less than the right operand, and False otherwise.

  • For Numbers: It performs a standard mathematical comparison.

Python

print(f"Is 10 < 20? {10 < 20}")

# Output: True

  • For Sequences (Strings, Lists, Tuples): It performs a lexicographical comparison. This means it compares items one by one from the beginning. The first difference it finds determines the result.

Python

print(f"Is 'apple' < 'banana'? {'apple' < 'banana'}")

# Output: True (because 'a' comes before 'b')

 

print(f"Is [1, 2, 9] < [1, 5]? {[1, 2, 9] < [1, 5]}")

# Output: True (it compares the first elements which are equal, then compares the second elements (2 < 5) and stops)


2. Increasing Power with Operator Overloading (__lt__)

You can define the behavior of the < operator for your own custom classes by implementing the __lt__ special method. This allows you to define a meaningful "less than" relationship that is specific to your class's logic.

Example: Comparing Recipe Objects

Let's extend the Recipe class from your Canvas. It's intuitive to say that one recipe is "less than" another if it produces fewer servings. We can implement this logic using __lt__.

Python

# --- 1. Define the Custom Class ---

class Recipe:

    """A class to represent a recipe with ingredients and servings."""

 

    def __init__(self, name, servings, ingredients):

        """

        The constructor for the class.

        """

        self.name = name

        self.servings = servings

        self.ingredients = ingredients

 

    def __repr__(self):

        """

        Provides a developer-friendly string representation of the object.

        """

        return (f"Recipe(name='{self.name}', servings={self.servings})")

 

    def __lt__(self, other):

        """

        This is the special method that defines the behavior of the '<' operator.

        It compares two Recipe objects based on their number of servings.

        """

        # Ensure we are comparing with another Recipe object.

        if not isinstance(other, Recipe):

            return NotImplemented

 

        # Return True if this recipe's servings are less than the other's.

        return self.servings < other.servings

 

# --- 2. Create Instances of the Class ---

large_cake_recipe = Recipe(

    name="Large Party Cake",

    servings=16,

    ingredients={"flour_grams": 400, "sugar_grams": 300, "eggs": 8}

)

 

small_cake_recipe = Recipe(

    name="Small Snack Cake",

    servings=8,

    ingredients={"flour_grams": 200, "sugar_grams": 150, "eggs": 4}

)

 

print("--- Original Recipes ---")

print(large_cake_recipe)

print(small_cake_recipe)

 

# --- 3. Use the '<' Operator on Custom Objects ---

# Because we defined the __lt__ method, we can now use the '<' operator

# to compare our two Recipe objects in an intuitive way.

if small_cake_recipe < large_cake_recipe:

    print(f"\nThe '{small_cake_recipe.name}' serves fewer people than the '{large_cake_recipe.name}'.")

else:

    print(f"\nThe '{large_cake_recipe.name}' serves fewer people than the '{small_cake_recipe.name}'.")

 

# You can also use it directly in boolean expressions.

is_smaller = small_cake_recipe < large_cake_recipe

print(f"Is the small cake recipe less than the large one? {is_smaller}")

 

>= (Greater than or equal to)

In Python, the >= operator is used in two main ways: for value comparison between built-in types and for creating powerful, custom logic for your own classes through operator overloading.

You can increase the power of your code by defining what "greater than or equal to" means for your own objects. This allows you to write comparisons that are both intuitive and highly readable, just like the __gt__ method in your Canvas code.


1. Value Comparison

This is the standard use of the >= operator. It compares two objects and returns True if the left operand is greater than or equal to the right operand, and False otherwise.

  • For Numbers: It performs a standard mathematical comparison.

Python

print(f"Is 20 >= 20? {20 >= 20}")

# Output: True

  • For Sequences (Strings, Lists, Tuples): It performs a lexicographical comparison. This means it compares items one by one from the beginning. The first difference it finds determines the result.

Python

print(f"Is 'banana' >= 'apple'? {'banana' >= 'apple'}")

# Output: True (because 'b' comes after 'a')

 

print(f"Is [1, 5] >= [1, 5]? {[1, 5] >= [1, 5]}")

# Output: True (all elements are equal)


2. Increasing Power with Operator Overloading (__ge__)

You can define the behavior of the >= operator for your own custom classes by implementing the __ge__ special method. This allows you to define a meaningful "greater than or equal to" relationship that is specific to your class's logic.

Example: Comparing Recipe Objects

Let's extend the Recipe class from your Canvas. It's intuitive to say that one recipe is "greater than or equal to" another if it produces the same number of servings or more. We can implement this logic using __ge__.

Python

# --- 1. Define the Custom Class ---

class Recipe:

    """A class to represent a recipe with ingredients and servings."""

 

    def __init__(self, name, servings, ingredients):

        """

        The constructor for the class.

        """

        self.name = name

        self.servings = servings

        self.ingredients = ingredients

 

    def __repr__(self):

        """

        Provides a developer-friendly string representation of the object.

        """

        return (f"Recipe(name='{self.name}', servings={self.servings})")

 

    def __ge__(self, other):

        """

        This is the special method that defines the behavior of the '>=' operator.

        It compares two Recipe objects based on their number of servings.

        """

        # Ensure we are comparing with another Recipe object.

        if not isinstance(other, Recipe):

            return NotImplemented

 

        # Return True if this recipe's servings are greater than or equal to the other's.

        return self.servings >= other.servings

 

# --- 2. Create Instances of the Class ---

large_cake_recipe = Recipe(

    name="Large Party Cake",

    servings=16,

    ingredients={"flour_grams": 400, "sugar_grams": 300, "eggs": 8}

)

 

another_large_recipe = Recipe(

    name="Another Large Cake",

    servings=16,

    ingredients={"flour_grams": 450, "sugar_grams": 320, "eggs": 9}

)

 

# --- 3. Use the '>=' Operator on Custom Objects ---

# Because we defined the __ge__ method, we can now use the '>=' operator

# to compare our two Recipe objects in an intuitive way.

if large_cake_recipe >= another_large_recipe:

    print(f"\nThe '{large_cake_recipe.name}' serves at least as many people as the '{another_large_recipe.name}'.")

 

# You can also use it directly in boolean expressions.

is_larger_or_equal = large_cake_recipe >= another_large_recipe

print(f"Is the first large cake recipe greater than or equal to the second one? {is_larger_or_equal}")

 

<= (Less than or equal to)

In Python, the <= operator is used in two main ways: for value comparison between built-in types and for creating powerful, custom logic for your own classes through operator overloading.

You can increase the power of your code by defining what "less than or equal to" means for your own objects. This allows you to write comparisons that are both intuitive and highly readable, just like the __gt__ method in your Canvas code.


1. Value Comparison

This is the standard use of the <= operator. It compares two objects and returns True if the left operand is less than or equal to the right operand, and False otherwise.

  • For Numbers: It performs a standard mathematical comparison.

Python

print(f"Is 10 <= 20? {10 <= 20}")

# Output: True

  • For Sequences (Strings, Lists, Tuples): It performs a lexicographical comparison. This means it compares items one by one from the beginning. The first difference it finds determines the result.

Python

print(f"Is 'apple' <= 'apple'? {'apple' <= 'apple'}")

# Output: True

 

print(f"Is [1, 2, 9] <= [1, 5]? {[1, 2, 9] <= [1, 5]}")

# Output: True (it compares the first elements which are equal, then compares the second elements (2 < 5) and stops)


2. Increasing Power with Operator Overloading (__le__)

You can define the behavior of the <= operator for your own custom classes by implementing the __le__ special method. This allows you to define a meaningful "less than or equal to" relationship that is specific to your class's logic.

Example: Comparing Recipe Objects

Let's extend the Recipe class from your Canvas. It's intuitive to say that one recipe is "less than or equal to" another if it produces the same number of servings or fewer. We can implement this logic using __le__.

Python

# --- 1. Define the Custom Class ---

class Recipe:

    """A class to represent a recipe with ingredients and servings."""

 

    def __init__(self, name, servings, ingredients):

        """

        The constructor for the class.

        """

        self.name = name

        self.servings = servings

        self.ingredients = ingredients

 

    def __repr__(self):

        """

        Provides a developer-friendly string representation of the object.

        """

        return (f"Recipe(name='{self.name}', servings={self.servings})")

 

    def __le__(self, other):

        """

        This is the special method that defines the behavior of the '<=' operator.

        It compares two Recipe objects based on their number of servings.

        """

        # Ensure we are comparing with another Recipe object.

        if not isinstance(other, Recipe):

            return NotImplemented

 

        # Return True if this recipe's servings are less than or equal to the other's.

        return self.servings <= other.servings

 

# --- 2. Create Instances of the Class ---

small_cake_recipe = Recipe(

    name="Small Snack Cake",

    servings=8,

    ingredients={"flour_grams": 200, "sugar_grams": 150, "eggs": 4}

)

 

another_small_recipe = Recipe(

    name="Another Small Cake",

    servings=8,

    ingredients={"flour_grams": 220, "sugar_grams": 160, "eggs": 4}

)

 

# --- 3. Use the '<=' Operator on Custom Objects ---

# Because we defined the __le__ method, we can now use the '<=' operator

# to compare our two Recipe objects in an intuitive way.

if small_cake_recipe <= another_small_recipe:

    print(f"\nThe '{small_cake_recipe.name}' serves at most as many people as the '{another_small_recipe.name}'.")

 

# You can also use it directly in boolean expressions.

is_smaller_or_equal = small_cake_recipe <= another_small_recipe

print(f"Is the first small cake recipe less than or equal to the second one? {is_smaller_or_equal}")

 

Arithmetic Operators Logical Operators
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website