Python Operators
Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.
6+3 9
Assignment operators
-
Assignment operators are used in Python to assign values to variables.
-
a = 5
is a simple assignment operator that assigns the value5
on the right to the variablea
on the left.
python +=
A little bit subtle or confusing in python is the plus equals
+=
operator
x = 1 x += 2 # add 2 to x print("x is",x) x <<= 3 # left shift by 2 print('x is',x) x **= 4 # x := x^2 print('x is',x)
The Above Code Outputs
x is 3 x is 24 x is 331776
Here's the table for Reference
Symbol | Example | Equivalent to |
---|---|---|
= | x = 5 | x = 5 |
+= | x += 5 | x = x + 5 |
-= | x -= 5 | x = x - 5 |
*= | x *= 5 | x = x * 5 |
/= | x /= 5 | x = x / 5 |
%= | x %= 5 | x = x % 5 |
//= | x //= 5 | x = x // 5 |
**= |
x **= 5 | x = x ** 5 |
&= x | &= 5 | x = x & 5 |
= | x | |
^= | x ^= 5 | x = x ^ 5 |
>>= | x >>= 5 | x = x >> 5 |
<<= | x <<= 5 | x = x << 5 |