As the name implies, these operators are used to assign values to variables.
x = 7
in the first example is a direct assignment storing the number 7
in the variable x
.
The assignment operation takes the value on the right and assigns it to the variable on the left.
The other operatores are simple shorthands for the Arithmetic Operators and the Bitwise Operators.
In the second example x
starts with 7
and x += 2
is just another way to write x = x + 2
, which means the previous value of x
is added by 2
and reassigned to x
that is now equals to 9
.
They are:
=
x = 7
print(x)
7
+=
x = 7
x += 2
print(x)
9
-=
x = 7
x -= 2
print(x)
5
*=
x = 7
x *= 2
print(x)
14
/=
x = 7
x /= 2
print(x)
3.5
%=
x = 7
x %= 2
print(x)
1
//=
x = 7
x //= 2
print(x)
3
**=
x = 7
x **= 2
print(x)
49
&=
x = 7
x &= 2
print(x)
2
|=
x = 7
x |= 2
print(x)
7
^=
x = 7
x ^= 2
print(x)
5
>>=
x = 7
x >>= 2
print(x)
1
<<=
x = 7
x <<= 2
print(x)
28