An operator is a symbol that tells Python to perform a specific operation on one or more values (called operands). Python provides several categories of operators.
Used to perform mathematical calculations.
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 5 - 3 | 2 |
* | Multiplication | 5 * 3 | 15 |
/ | Division (float) | 5 / 2 | 2.5 |
// | Floor Division | 5 // 2 | 2 |
% | Modulus | 7 % 3 | 1 |
** | Exponentiation | 2 ** 3 | 8 |
/ always returns a float: // returns the largest integer ≤ result: % returns the remainder: ** is right-associative: print(10 / 3) # 3.3333...
print(10 // 3) # 3
print(10 % 3) # 1
print(2 ** 8) # 256
Used to compare two values. They return True or False.
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | 5 == 5 → True |
!= | Not equal to | 5 != 3 → True |
> | Greater than | 5 > 3 → True |
< | Less than | 3 < 5 → True |
>= | Greater than or equal | 5 >= 5 → True |
<= | Less than or equal | 3 <= 5 → True |
Used to assign values to variables.
| Operator | Example | Equivalent |
|---|---|---|
= | x = 5 | Assign 5 to x |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
//= | x //= 3 | x = x // 3 |
%= | x %= 3 | x = x % 3 |
**= | x **= 3 | x = x ** 3 |
Note: == is a comparison operator, NOT an assignment operator.
Used to combine conditional (Boolean) expressions.
| Operator | Description | Example |
|---|---|---|
and | True if both operands are True | True and False → False |
or | True if at least one operand is True | True or False → True |
not | Reverses the logical state | not True → False |
x = 10
print(x > 5 and x < 20) # True
print(x > 5 or x > 20) # True
print(not(x > 5)) # False
Bitwise operators act on operands as binary strings, performing operations bit by bit.
| Operator | Name | Example ( & ) |
|---|---|---|
& | AND | 101 & 011 = 001 → 1 |
| | OR | 101 | 011 = 111 → 7 |
^ | XOR | 101 ^ 011 = 110 → 6 |
~ | NOT | ~5 = -6 |
<< | Left Shift | 5 << 1 = 10 |
>> | Right Shift | 5 >> 1 = 2 |
x = 5 # binary: 101
y = 3 # binary: 011
print(x & y) # 1
print(x | y) # 7
print(x ^ y) # 6
Python evaluates operators in this order (highest to lowest):
** (Exponentiation)~, +, - (Unary)*, /, //, %+, -<<, >>&^|notandor