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

= (Simple Assignment): Assigns the value on the right to the variable on the left.

In Python, the = (Simple Assignment) operator is used in two main ways: for single variable assignment and for a powerful technique called multiple assignment (or iterable unpacking).


1. Single Variable Assignment

This is the most fundamental use of the = operator. It takes the value from the right-hand side and assigns it to the variable on the left-hand side.

Example:

Python

# The value 16 is assigned to the variable 'servings'

servings = 16

 

# The Recipe object is created and then assigned to the variable 'large_cake_recipe'

large_cake_recipe = Recipe(

    name="Large Party Cake",

    servings=16,

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

)


2. Increasing Power with Multiple Assignment

This is a more advanced and powerful feature that allows you to write more concise and readable code. You can assign values from a sequence (like a list or tuple) to multiple variables in a single line.

This technique is powerful because it can make your code cleaner and reduce the number of lines needed to assign variables.

Example: Unpacking a Tuple

Python

# Create a tuple

point = (10, 20)

 

# Use multiple assignment to unpack the tuple into two variables

x, y = point

 

print(f"x: {x}") # Output: 10

print(f"y: {y}") # Output: 20

Example: Using it with your Recipe Class

You can use multiple assignment to elegantly extract information from your Recipe objects.

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 get_details(self):

        """Returns the core details as a tuple."""

        return self.name, self.servings

 

# Create a recipe object

cake_recipe = Recipe("Vanilla Cake", 12, {"flour": 300, "sugar": 200})

 

# Use multiple assignment to get the details in one line

recipe_name, recipe_servings = cake_recipe.get_details()

 

print(f"Recipe Name: {recipe_name}")

print(f"Servings: {recipe_servings}")

 

+=, -=, *=, /=, etc. (Compound Assignment): These combine an arithmetic operation with an assignment. For example, x += 5 is a shorthand for x = x + 5.

In Python, compound assignment operators combine a standard operation (like addition or multiplication) with an assignment. They provide a concise shorthand for modifying a variable in place.

there are 12 compound assignment operators, which are divided into two main categories: Arithmetic and Bitwise.

  • Arithmetic: +=, -=, *=, /=, %=, //=, **=

  • Bitwise: &=, |=, ^=, >>=, <<=

You can increase the power of your code by using these operators to write more concise, readable, and efficient code, especially when working with mutable objects or your own custom classes.

You can increase the power of your code using these operators in three key ways:

1.   Conciseness: They provide a shorter, more readable way to write code that modifies a variable.

2.   Efficiency: For mutable objects like lists, they perform modifications "in-place," which can be more memory-efficient.

3.   Operator Overloading: You can define their behavior for your own custom classes to create powerful, intuitive, and domain-specific logic.

 

Here is  of each operator.


Arithmetic Compound Assignment Operators

These operators combine a standard mathematical operation with an assignment.

+= (Addition Assignment)

  • Explanation: Adds the right operand to the left operand and assigns the result back to the left operand. For sequences like lists, it performs in-place concatenation.

  • Code:

Python

# Standard Use

score = 100

score += 10  # Equivalent to score = score + 10

print(f"Score: {score}") # Output: 110

 

# Powerful Use (In-place list modification)

items = [1, 2, 3]

items += [4, 5] # Extends the original list

print(f"Items: {items}") # Output: [1, 2, 3, 4, 5]

-= (Subtraction Assignment)

  • Explanation: Subtracts the right operand from the left operand and assigns the result back to the left operand.

  • Code:

Python

# Standard Use

health = 100

health -= 25 # Equivalent to health = health - 25

print(f"Health: {health}") # Output: 75

*= (Multiplication Assignment)

  • Explanation: Multiplies the left operand by the right operand and assigns the result back. For sequences, it performs in-place repetition.

  • Code:

Python

# Standard Use

value = 5

value *= 3 # Equivalent to value = value * 3

print(f"Value: {value}") # Output: 15

 

# Powerful Use (In-place list repetition)

pattern = ['a', 'b']

pattern *= 3

print(f"Pattern: {pattern}") # Output: ['a', 'b', 'a', 'b', 'a', 'b']

/= (Division Assignment)

  • Explanation: Divides the left operand by the right operand and assigns the (always float) result back.

  • Code:

Python

# Standard Use

distance = 100.0

distance /= 4 # Equivalent to distance = distance / 4

print(f"Distance: {distance}") # Output: 25.0

//= (Floor Division Assignment)

  • Explanation: Performs floor division and assigns the rounded-down result back.

  • Code:

Python

# Standard Use

items = 25

items_per_box = 4

items //= items_per_box # Equivalent to items = items // items_per_box

print(f"Full boxes: {items}") # Output: 6

%= (Modulus Assignment)

  • Explanation: Calculates the remainder and assigns it back to the left operand.

  • Code:

Python

# Standard Use

total_items = 25

items_per_box = 4

total_items %= items_per_box # Equivalent to total_items = total_items % items_per_box

print(f"Items left over: {total_items}") # Output: 1

**= (Exponentiation Assignment)

  • Explanation: Raises the left operand to the power of the right operand and assigns the result back.

  • Code:

Python

# Standard Use

number = 2

number **= 5 # Equivalent to number = number ** 5

print(f"Number to the power of 5: {number}") # Output: 32


Bitwise Compound Assignment Operators

These operators perform a bitwise operation and assign the result back. They are used for low-level manipulation of integers.

&= (Bitwise AND Assignment)

  • Explanation: Performs a bitwise AND on the operands and assigns the result back.

  • Code:

Python

# 5 is 0101 in binary

# 3 is 0011 in binary

flags = 5

mask = 3

flags &= mask # 0101 & 0011 = 0001

print(f"Flags after AND mask: {flags}") # Output: 1

|= (Bitwise OR Assignment)

  • Explanation: Performs a bitwise OR on the operands and assigns the result back.

  • Code:

Python

# 5 is 0101 in binary

# 3 is 0011 in binary

flags = 5

mask = 3

flags |= mask # 0101 | 0011 = 0111

print(f"Flags after OR mask: {flags}") # Output: 7

^= (Bitwise XOR Assignment)

  • Explanation: Performs a bitwise XOR (exclusive OR) and assigns the result back.

  • Code:

Python

# 5 is 0101 in binary

# 3 is 0011 in binary

flags = 5

mask = 3

flags ^= mask # 0101 ^ 0011 = 0110

print(f"Flags after XOR mask: {flags}") # Output: 6

>>= (Bitwise Right Shift Assignment)

  • Explanation: Performs a bitwise right shift and assigns the result back.

  • Code:

Python

# 8 is 1000 in binary

value = 8

value >>= 2 # Shift right by 2 bits: 1000 -> 0010

print(f"Value after right shift by 2: {value}") # Output: 2

<<= (Bitwise Left Shift Assignment)

  • Explanation: Performs a bitwise left shift and assigns the result back.

  • Code:

Python

# 2 is 0010 in binary

value = 2

value <<= 2 # Shift left by 2 bits: 0010 -> 1000

print(f"Value after left shift by 2: {value}") # Output: 8

 

Operator Overloading:

In Python, you can define the behavior of compound assignment operators (like +=, *=, etc.) for your own custom classes. This is done by implementing special "in-place" methods. The key difference from regular operator methods (like __add__) is that these in-place methods are expected to modify the object itself (self) and then return self.

This allows you to create efficient and intuitive logic. For example, my_vector += another_vector can modify my_vector directly without creating a new object, which can be more performant.

I have prepared for you that contains a detailed code example using a Vector2D class, where each of the 12 compound assignment operators has been overloaded with a specific meaning.

 

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

# A simple class to represent a 2D vector with x and y components.

class Vector2D:

    def __init__(self, x, y):

        self.x = x

        self.y = y

 

    def __repr__(self):

        """Provides a developer-friendly string representation."""

        return f"Vector2D({self.x}, {self.y})"

 

    # --- Arithmetic Compound Assignment Overloads ---

 

    def __iadd__(self, other):

        """Defines the behavior for the '+=' operator (in-place addition)."""

        if isinstance(other, Vector2D):

            self.x += other.x

            self.y += other.y

            return self # Must return self

        return NotImplemented

 

    def __isub__(self, other):

        """Defines the behavior for the '-=' operator (in-place subtraction)."""

        if isinstance(other, Vector2D):

            self.x -= other.x

            self.y -= other.y

            return self

        return NotImplemented

 

    def __imul__(self, scalar):

        """Defines the behavior for the '*=' operator (in-place scalar multiplication)."""

        if isinstance(scalar, (int, float)):

            self.x *= scalar

            self.y *= scalar

            return self

        return NotImplemented

 

    def __itruediv__(self, scalar):

        """Defines the behavior for the '/=' operator (in-place scalar division)."""

        if isinstance(scalar, (int, float)):

            self.x /= scalar

            self.y /= scalar

            return self

        return NotImplemented

       

    def __ifloordiv__(self, scalar):

        """Defines the behavior for the '//=' operator (in-place floor division)."""

        if isinstance(scalar, (int, float)):

            self.x //= scalar

            self.y //= scalar

            return self

        return NotImplemented

 

    def __imod__(self, scalar):

        """Defines the behavior for the '%=' operator (in-place modulus)."""

        if isinstance(scalar, (int, float)):

            self.x %= scalar

            self.y %= scalar

            return self

        return NotImplemented

 

    def __ipow__(self, power):

        """Defines the behavior for the '**=' operator (in-place exponentiation)."""

        if isinstance(power, (int, float)):

            self.x **= power

            self.y **= power

            return self

        return NotImplemented

 

    # --- Bitwise Compound Assignment Overloads ---

    # These operate on the integer parts of the vector's components.

 

    def __iand__(self, other):

        """Defines the behavior for the '&=' operator (in-place bitwise AND)."""

        if isinstance(other, Vector2D):

            self.x &= int(other.x)

            self.y &= int(other.y)

            return self

        return NotImplemented

 

    def __ior__(self, other):

        """Defines the behavior for the '|=' operator (in-place bitwise OR)."""

        if isinstance(other, Vector2D):

            self.x |= int(other.x)

            self.y |= int(other.y)

            return self

        return NotImplemented

 

    def __ixor__(self, other):

        """Defines the behavior for the '^=' operator (in-place bitwise XOR)."""

        if isinstance(other, Vector2D):

            self.x ^= int(other.x)

            self.y ^= int(other.y)

            return self

        return NotImplemented

 

    def __irshift__(self, bits):

        """Defines the behavior for the '>>=' operator (in-place right shift)."""

        if isinstance(bits, int):

            self.x >>= bits

            self.y >>= bits

            return self

        return NotImplemented

 

    def __ilshift__(self, bits):

        """Defines the behavior for the '<<=' operator (in-place left shift)."""

        if isinstance(bits, int):

            self.x <<= bits

            self.y <<= bits

            return self

        return NotImplemented

 

# --- 2. Demonstration ---

 

print("--- Arithmetic Compound Assignments ---")

v1 = Vector2D(10, 20)

v2 = Vector2D(3, 5)

print(f"Original v1: {v1}")

v1 += v2

print(f"After v1 += v2: {v1}")

 

v1 = Vector2D(10, 20)

v1 *= 2

print(f"After v1 *= 2: {v1}")

 

v1 = Vector2D(10.5, 20.5)

v1 //= 3

print(f"After v1 //= 3: {v1}")

 

print("\n--- Bitwise Compound Assignments ---")

v_bit1 = Vector2D(12, 5) # Binary: 1100, 0101

v_bit2 = Vector2D(10, 3) # Binary: 1010, 0011

print(f"Original v_bit1: {v_bit1}")

v_bit1 &= v_bit2 # 1100 & 1010 = 1000 (8); 0101 & 0011 = 0001 (1)

print(f"After v_bit1 &= v_bit2: {v_bit1}")

 

v_bit1 = Vector2D(12, 5)

v_bit1 |= v_bit2 # 1100 | 1010 = 1110 (14); 0101 | 0011 = 0111 (7)

print(f"After v_bit1 |= v_bit2: {v_bit1}")

 

v_shift = Vector2D(16, 8) # Binary: 10000, 1000

print(f"Original v_shift: {v_shift}")

v_shift >>= 2 # 10000 >> 2 = 00100 (4); 1000 >> 2 = 0010 (2)

print(f"After v_shift >>= 2: {v_shift}")

 

Logical Operators Identity 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