Assignment Operators
Assignment Operators
Name | Symbol | Syntax | Explanation |
Assignment | = |
| Assigns the value of |
Add and assign | += |
| Add |
Subtract and assign | -= |
| Subtracts |
Multiply and assign | *= |
| Multiplies |
Divide and assign | /= |
| Divides |
Floor divide and assign | //= |
| Divides |
Exponent and assign | **= |
| Raises |
Modulo and assign | %= |
| Calculates the remainder when |
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.
num = 6num2 = 0num2 = numprint(num2)num += 3print(num)num -= 3print(num)num *= 3print(num)num /= 3print(num)num //= 3print(num)num **= 3print(num)num %= 3print(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.
num_one = 6num_two = 3print(num_one)num_one += num_twoprint(num_one)num_one -= num_twoprint(num_one)num_one *= num_twoprint(num_one)num_one /= num_twoprint(num_one)num_one //= num_twoprint(num_one)num_one **= num_twoprint(num_one)num_one %= num_twoprint(num_one)