Lesson Contents
Python assignment operators are one of the operator types and assign values to variables. We use arithmetic operators here in combination with a variable.
Let’s take a look at some examples.
Operator Assignment (=)
This is the most basic assignment operator and we used it before in the lessons about lists, tuples, and dictionaries. For example, we can assign a value (integer) to a variable:
>>> x = 4
>>> print(x)
Will show this output:
4
Operator Addition (+=)
We can add a number to our variable like this:
>>> x = 4
>>> x += 1
>>> print(x)
Will show this output:
5
Using the above operator is the same as doing this:
>>> x = 4
>>> x = x + 1
>>> print(x)
Will show the same output:
5
The += operator is shorter to write but the end result is the same.
Operator Subtraction (-=)
We can also subtract a value. For example:
>>> x = 4
>>> x -= 2
>>> print(x)
Will show this output:
2
Using this operator is the same as doing this:
>>> x = 4
>>> x = x - 2
>>> print(x)
Will show the same output:
2
Operator Multiplication (*=)
We can also use multiplication. We’ll multiply our variable by 4:
>>> x = 4
>>> x *= 4
>>> print(x)
Will show this output:
16
Which is similar to:
>>> x = 4
>>> x = x * 4
>>> print(x)
Will show the same output:
16
Operator Division (/=)
Let’s try the divide operator:
>>> x = 16
>>> x /= 4
>>> print(x)
Will show this output:
4.0
This is the same as:
>>> x = 16
>>> x = x / 4
>>> print(x)
Will show the same output:
4.0
Operator Modulus (%=)
We can also calculate the modulus. How about this:
>>> x = 4
>>> x %= 3
>>> print(x)
Will show this output:
1
This is the same as doing it like this:
>>> x = 4
>>> x = x % 3
>>> print(x)
Will show the same output:
1
Operator Exponentiation (**=)
How about exponentiation? Let’s give it a try:
>>> x = 2
>>> x **= 4
>>> print(x)
Will show this output:
16
Which is the same as doing it like this: