StudyLover
  • Home
  • Study Zone
  • Profiles
  • Typing Tutor
  • Contact us
  • Sign in
StudyLover Logical 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
Comparison (Relational) Operators : Assignment Operators
Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP

AND: Returns True if both operands are true.

In Python, the logical and operator is used in two main ways: for combining boolean expressions and for a powerful technique called short-circuiting with any type of object.


1. Combining Boolean Expressions

This is the most common use of the and operator. It takes two boolean values (or expressions that evaluate to a boolean) and returns True only if both of its operands are True.

Expression

Result

True and True

True

True and False

False

False and True

False

False and False

False

Example Code:

Python

age = 25

has_license = True

 

# Check if the person is eligible to rent a car

if age >= 25 and has_license:

    print("Eligible to rent a car.")

else:

    print("Not eligible to rent a car.")


2. Increasing Power with Short-Circuiting and "Truthiness"

This is a more advanced and powerful feature of the and operator. It doesn't just work with True or False; it can work with any Python object.

  • Short-Circuiting Behavior: When evaluating a and b, Python first looks at a. If a is "falsy" (e.g., False, 0, None, or an empty list/string), the entire expression must be false, so Python stops and immediately returns the value of a. It never even looks at b. This is called "short-circuiting." If a is "truthy," Python then evaluates and returns the value of b.

This behavior is powerful because it allows you to write safe, concise code.

Example: Preventing Errors

You can use short-circuiting to prevent an error when checking an attribute of an object that might be None.

Python

my_list = None

 

# This code will NOT cause an error because the `and` operator short-circuits.

# It checks `my_list is not None`, finds it's False, and stops before trying to access `len(my_list)`.

if my_list is not None and len(my_list) > 0:

    print("The list has items.")

else:

    print("The list is either None or empty.")

Example: Using it in Your Recipe Class

You can use and to make the comparison logic in your Recipe class from the Canvas more robust. For example, you could say one recipe is "greater" than another only if it serves more people and has more ingredients.

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})")

 

    def __gt__(self, other):

        """

        Defines '>' to mean more servings AND more or equal ingredients.

        """

        if not isinstance(other, Recipe):

            return NotImplemented

 

        # Use 'and' to combine multiple logical conditions

        return self.servings > other.servings and len(self.ingredients) >= len(other.ingredients)

 

# Create two recipe objects

large_recipe = Recipe("Large Cake", 16, {"flour": 400, "sugar": 300, "eggs": 8})

small_recipe = Recipe("Small Cake", 8, {"flour": 200, "sugar": 150}) # Fewer ingredients

 

# This comparison now uses the powerful, combined logic

if large_recipe > small_recipe:

    print("The large recipe is bigger in both servings and ingredient count.")

 

# Output: The large recipe is bigger in both servings and ingredient count.

 

 

OR: Returns True if at least one of the operands is true.

In Python, the logical or operator is used in two main ways: for combining boolean expressions and for a powerful technique called short-circuiting, which is excellent for providing default values.


1. Combining Boolean Expressions

This is the most common use of the or operator. It takes two boolean values (or expressions that evaluate to a boolean) and returns True if at least one of its operands is True.

Expression

Result

True or True

True

True or False

True

False or True

True

False or False

False

Example Code:

Python

has_coupon = True

is_member = False

 

# Check if the customer gets a discount

if has_coupon or is_member:

    print("Applying discount.")

else:

    print("No discount applied.")


2. Increasing Power with Short-Circuiting and "Truthiness"

This is a more advanced and powerful feature of the or operator. It doesn't just work with True or False; it can work with any Python object.

  • Short-Circuiting Behavior: When evaluating a or b, Python first looks at a. If a is "truthy" (e.g., a non-empty string, a non-zero number, or a non-empty list), the entire expression must be true, so Python stops and immediately returns the value of a. It never even looks at b. If a is "falsy" (e.g., False, 0, None, or an empty list/string), Python then evaluates and returns the value of b.

This behavior is powerful because it allows you to write concise code for providing default values.

Example: Providing a Default Value

You can use short-circuiting to provide a default username if the user's input is empty.

Python

user_input = "" # The user didn't enter anything

 

# If user_input is an empty string (falsy), the expression returns the value on the right.

username = user_input or "Guest"

 

print(f"Username: {username}")

# Output: Username: Guest

Example: Using it in Your Recipe Class

You can use or to make the comparison logic in your Recipe class from the Canvas more sophisticated. For example, you could say one recipe is "greater" than another if it serves more people, or if the servings are equal, if it has more ingredients.

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})")

 

    def __gt__(self, other):

        """

        Defines '>' to mean more servings OR (if servings are equal) more ingredients.

        """

        if not isinstance(other, Recipe):

            return NotImplemented

 

        # Use 'or' to create a two-level comparison logic

        return self.servings > other.servings or (self.servings == other.servings and len(self.ingredients) > len(other.ingredients))

 

# Create two recipe objects

recipe_a = Recipe("Cake", 8, {"flour": 200, "sugar": 150, "eggs": 4})

recipe_b = Recipe("Cookies", 8, {"flour": 150, "sugar": 100}) # Same servings, fewer ingredients

 

# This comparison now uses the powerful, combined logic

if recipe_a > recipe_b:

    print("Recipe A is considered 'greater' because it has more ingredients for the same number of servings.")

 

# Output: Recipe A is considered 'greater' because it has more ingredients for the same number of servings.

 

not: Inverts the truth value; returns False if the operand is true, and True if it is false.

In Python, the logical not operator is a unary operator (meaning it only takes one operand) used in two main ways: for inverting boolean values and for checking the "truthiness" of any object.


1. Inverting Boolean Values

This is the most direct use of the not operator. It simply flips a boolean value:

  • not True evaluates to False.

  • not False evaluates to True.

This is fundamental for controlling program flow in conditional statements.

Example Code:

Python

is_authenticated = False

 

# Use 'not' to check for the opposite condition

if not is_authenticated:

    print("Access denied. Please log in.")

else:

    print("Welcome!")

 

# Output: Access denied. Please log in.


2. Increasing Power with "Truthiness"

This is a more advanced and powerful feature. The not operator doesn't just work on True or False; it can be applied to any Python object to check its "truthiness."

In Python, most objects are considered "truthy," except for a few specific "falsy" values:

  • The number 0

  • An empty string ""

  • An empty list [], tuple (), or dictionary {}

  • The special value None

The not operator will return True for any "falsy" object and False for any "truthy" object. This allows you to write very clean and readable code for checking if a collection is empty or if a variable has a value.

Example: Checking for an Empty List

Python

shopping_list = []

 

# Using 'not' is a concise and Pythonic way to check if a list is empty.

if not shopping_list:

    print("Your shopping list is empty. Please add some items.")

 

# This is more readable than the alternative: if len(shopping_list) == 0:

Example: Using it with Your Recipe Class

You can make the not operator work with your Recipe class from the Canvas by defining the __bool__ special method. This method tells Python how to determine if an instance of your class is "truthy" or "falsy." Let's say a recipe is "falsy" if it has no ingredients.

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})")

 

    def __bool__(self):

        """

        Defines the 'truthiness' of a Recipe object.

        Returns True if there are ingredients, False otherwise.

        """

        return len(self.ingredients) > 0

 

# Create two recipe objects

full_recipe = Recipe("Cake", 8, {"flour": 200, "sugar": 150})

empty_recipe = Recipe("Empty Recipe", 0, {})

 

# Now we can use 'not' in a very intuitive way on our custom objects.

if not empty_recipe:

    print("The 'Empty Recipe' has no ingredients and is considered falsy.")

 

if full_recipe: # This checks if the recipe is "truthy"

    print("The 'Cake' recipe has ingredients and is considered truthy.")

 

 

Comparison (Relational) Operators Assignment 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