There are five groups of operators in the Python programming language: arithmetic, comparison, assignment, logical, identity, membership, and bitwise.
- Arithmetic operators – are used to perform basic mathematical operations
- Comparison operators – are used to compare values, they return a True/False based on the statement
- Assignment operators – are used to perform some operation and assign a value to a variable
- Logical operators – are used to combine conditional statements
- Identity operators – are used to determine if objects are the same
- Membership operators – are used to determine if a value is found in a sequence
- Bitwise operators – are used to perform operations at the bit level
Combining Operators
You can combine various operators together:
>>> x = 3
>>> (x < 5 + 1) and (x > 1)
True
Arithmetic Operators
Operator | Description | Example |
---|---|---|
+ | Addition | 8 + 3 = 11 |
– | Subtraction | 8 – 3 = 5 |
* | Multiplication | 8 * 3 = 24 |
/ | Division | 8 / 3 = 2.66… |
// | Floor division – round down division | 16//3 = 5 |
% | Modulo operation – remainder from division | 16%3 = 1 |
** | Power operation | 2**3 = 8 |
Order of operation
In Python, just like in Math order of arithmetic operations is governed by PEMDAS – Parentheses, Exponent, Multiplication, Division, Addition, Subtraction.
>>> 3 + 2 * 8
19
>>> (3 + 2) * 8
40
Comparison Operators
Operator | Description | Example |
---|---|---|
== | Equal | a == b |
!= | Not equal | a != b |
> | Greater than | a > b |
< | Less than | a < b |
>= | Greater than or equal | a >= b |
<= | Less than or equal | a <= b |
Assignment Operators
Operator | Description | Example |
---|---|---|
= | Assignment | x = 5 |
+= | Addition assignment | x += 5 |
-= | Subtraction assignment | x -= 5 |
*= | Multiplication assignment | x *= 5 |
/= | Division assignment | x /= 5 |
%= | Modulus assignment | x %= 5 |
//= | Floor division assignment | x //= 5 |
**= | Power assignment | x **= 5 |
&= | Bitwise AND assignment | x &= 5 |
|= | Bitwise OR assignment | x != 5 |
^= | Bitwise XOR assignment | x ^= 5 |
>>= | Bitwise shift right assignment | x >>= 5 |
<<= | Bitwise shift left assignment | x <<= 5 |
Logical Operators
Operator | Description | Example |
---|---|---|
and | And logical operation | x > 3 and x < 8 |
or | Or logical operation | x < 3 or x > 8 |
not | Not logical operation | not x |
Identity Operators
Operator | Description | Example |
---|---|---|
is | Is the same object | x is y |
is not | Is not the same object | x is not y |
Membership Operators
Operator | Description | Example |
---|---|---|
in | In a sequence | x in [1, 2, 3] |
not in | Not in a sequence | x not in [1, 2, 3] |
Bitwise Operators
Operator | Description | Example |
---|---|---|
& | Bitwise AND | x & 5 |
| | Bitwise OR | x | 5 |
^ | Bitwise XOR | x ^ 5 |
<< | Bitwise shift left | x << 5 |
>> | Bitwise shift right | x >> 5 |