Python

In Python, Assignment Operators are used to assign values to variables. While the basic assignment operator is the equals sign (=), Python provides a variety of compound assignment operators (also known as augmented assignment operators) that allow you to perform an arithmetic operation and an assignment in a single step.

1. Theoretical Overview

Assignment operators act as a shorthand for updating the value of a variable based on its current value. For example, instead of writing x = x + 5, you can simply write x += 5.

List of Assignment Operators

OperatorExampleEquivalent toDescription
=x = 5x = 5Assigns the value on the right to the variable on the left.
+=x += 3x = x + 3Adds the right operand to the left and assigns the result.
-=x -= 3x = x - 3Subtracts the right operand from the left and assigns the result.
*=x *= 3x = x * 3Multiplies the left operand by the right and assigns the result.
/=x /= 3x = x / 3Divides the left operand by the right and assigns the result (float).
//=x //= 3x = x // 3Floor divides the left operand and assigns the integer result.
%=x %= 3x = x % 3Takes the modulus and assigns the remainder.
**=x **= 3x = x ** 3Performs exponentiation and assigns the result.

2. Why Use Compound Assignment?

  1. Efficiency: It is slightly faster for the computer to process in certain contexts.

  2. Readability: It reduces redundancy. You don't have to type the variable name twice.

  3. Clean Code: It makes the intention of "updating" a variable clear to anyone reading the code.

3. Code Implementation

Python
# Basic Assignment
count = 10
print(f"Initial count: {count}")

# Addition Assignment
count += 5  # Equivalent to count = count + 5
print(f"After += 5: {count}")

# Subtraction Assignment
count -= 2  # Equivalent to count = count - 2
print(f"After -= 2: {count}")

# Multiplication Assignment
count *= 2  # Equivalent to count = count * 2
print(f"After *= 2: {count}")

# Division Assignment
count /= 4  # Equivalent to count = count / 4
print(f"After /= 4: {count}")

# Modulus Assignment
val = 10
val %= 3    # Equivalent to val = val % 3
print(f"Remainder of 10/3: {val}")

# Exponent Assignment
power = 2
power **= 3 # Equivalent to power = power ** 3
print(f"2 to the power of 3: {power}")

4. Special Case: Assignment Expressions (The Walrus Operator)

Introduced in Python 3.8, the Walrus Operator (:=) allows you to assign a value to a variable as part of an expression. This is advanced but very useful in loops or conditional checks.

Python
# Example: Assigning and checking a length in one line
if (n := len("Python")) > 5:
    print(f"The word is long ({n} characters).")
Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now