Python Assignment Operators: Explained with Examples
Assignment operators in Python are used to assign values to variables. While the basic assignment operator is =
, Python also supports compound assignment operators like +=
, -=
, *=
, and more, which make expressions more concise and efficient.
Let’s explore all the commonly used assignment operators through practical examples.
Example 1: Basic Assignment (=)
x = 10
print(x)
The =
operator assigns the value on the right to the variable on the left.
Example 2: Add and Assign (+=)
score = 50
score += 20
print(score)
score += 20
is equivalent to score = score + 20
. Output: 70
Example 3: Subtract and Assign (-=)
balance = 1000
balance -= 200
print(balance)
Subtracts 200 from balance. Output: 800
Example 4: Multiply and Assign (*=)
count = 5
count *= 3
print(count)
Multiplies count by 3. Output: 15
Example 5: Divide and Assign (/=)
total = 100
total /= 4
print(total)
Divides total by 4. Output: 25.0
Example 6: Floor Divide and Assign (//=)
items = 17
items //= 3
print(items)
Performs floor division and updates the variable. Output: 5
Example 7: Modulus and Assign (%=)
remainder = 10
remainder %= 4
print(remainder)
Assigns the remainder of the division to the variable. Output: 2
Example 8: Exponent and Assign (**=)
power = 2
power **= 4
print(power)
Raises the value to the power of 4 and updates it. Output: 16
Example 9: Chained Assignment
a = b = c = 100
print(a, b, c)
All variables are assigned the same value in one line.
Example 10: Using Assignment in a Loop
counter = 0
for i in range(5):
counter += 1
print(counter)
+=
is often used to accumulate values in loops. Output: 5
Summary
=
: Basic assignment+=
: Add and assign-=
: Subtract and assign*=
: Multiply and assign/=
: Divide and assign (float)//=
: Floor divide and assign%=
: Modulus and assign**=
: Exponent and assign
Assignment operators help make code shorter and cleaner. They're especially useful when updating variables repeatedly, such as in loops, counters, and accumulators.