Assignment Operators

Name

Symbol

Syntax

Explanation

Assignment

=

var_1 = var_2

Assigns the value of var_2 to var_1

Add and assign

+=

var_1 += var_2

Add var_2 to var_1 and assigns the result to var_1

Subtract and assign

-=

var_1 -= var_2

Subtracts var_2 from var_1 and assigns the result to var_1

Multiply and assign

*=

var_1 *= var_2

Multiplies var_1 by var_2 and assigns the result to var_1

Divide and assign

/=

var_1 /= var_2

Divides var_1 with var_2 and assigns the result to var_1; the result is always a float

Floor divide and assign

//=

var_1 //= var_2

Divides var_1 with var_2 and assigns the result to var_1; the result will be dependent on the type of values used

Exponent and assign

**=

var_1 **= var_2

Raises var_1 to the power of var_2 and assigns the result to var_1

Modulo and assign

%=

var_1 %= var_2

Calculates the remainder when var_1 is divided by var_2 and assigns the result to var_1

For demonstration purposes, let’s use a single variable, num. Initially, we set num to 6. We can apply all of these operators to num and update it accordingly.

Assignment

Assigning the value of 6 to num results in num being 6.

Expression: num = 6

Add and assign

Adding 3 to num and assigning the result back to num would result in 9.

Expression: num += 3

Subtract and assign

Subtracting 3 from num and assigning the result back to num would result in 6.

Expression: num -= 3

Multiply and assign

Multiplying num by 3 and assigning the result back to num would result in 18.

Expression: num *= 3

Divide and assign

Dividing num by 3 and assigning the result back to num would result in 6.0 (always a float).

Expression: num /= 3

Floor divide and assign

Performing floor division on num by 3 and assigning the result back to num would result in 2.

Expression: num //= 3

Exponent and assign

Raising num to the power of 3 and assigning the result back to num would result in 216.

Expression: num **= 3

Modulo and assign

Calculating the remainder when num is divided by 3 and assigning the result back to num would result in 2.

Expression: num %= 3

Code

We can effectively put this into Python code, and you can experiment with the code yourself! Click the “Run” button to see the output.

Press + to interact
num = 6
num2 = 0
num2 = num
print(num2)
num += 3
print(num)
num -= 3
print(num)
num *= 3
print(num)
num /= 3
print(num)
num //= 3
print(num)
num **= 3
print(num)
num %= 3
print(num)

The above code is useful when we want to update the same number. We can also use two different numbers and use the assignment operators to apply them on two different values.

Press + to interact
num_one = 6
num_two = 3
print(num_one)
num_one += num_two
print(num_one)
num_one -= num_two
print(num_one)
num_one *= num_two
print(num_one)
num_one /= num_two
print(num_one)
num_one //= num_two
print(num_one)
num_one **= num_two
print(num_one)
num_one %= num_two
print(num_one)