Python Operators:
Python Operators Overview
Python supports several types of operators:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators
7. Membership Operators
1. Arithmetic Operators
Used for mathematical operations.
Operator Meaning Example Result
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division 5 / 2 2.5
// Floor Division 5 // 2 2
% Modulus 5 % 2 1
** Exponentiation 5 ** 2 25
Note: / always returns a float; // returns the integer part (floor).
2
2. Comparison (Relational) Operators
Return True or False.
Operator Meaning Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 5 > 3 True
< Less than 5 < 3 False
>= Greater than or equal 5 >= 5 True
<= Less than or equal 5 <= 3 False
These work with numbers, strings (lexicographically), and other comparable
types.
3. Logical Operators
Combine boolean expressions.
Operator Meaning Example Result
and AND (5 > 3) and (2 < 4) True
or OR (5 < 3) or (2 < 4) True
not NOT not (5 < 3) True
and → both must be True; or → at least one True; not flips the value.
4. Bitwise Operators
Operate on binary representations.
Operator Name Example Result
& AND 5 & 3 1
| OR 5 | 3 7
ˆ XOR 5 ^ 3 6
˜ NOT (1’s comp) ~05 -6
« Left shift 5 << 1 10
» Right shift 5 >> 1 2
Useful in low-level programming or optimization. (5 = 101, 3 = 011)
3
5. Assignment Operators
Assign values to variables (with shortcuts).
Operator Equivalent to
= —
+= x = x + 3
-= x = x - 3
*= x = x * 3
/= x = x / 3
//= x = x // 3
%= x = x % 3
**= x = x ** 3
&=, |=, ˆ=, «=, »= Similar pattern
Helps write concise code. Example: x += 3 is shorter than x = x + 3.
6. Identity Operators
Check if two variables refer to the same object (not just equal value).
Operator Example Result
is a = [1,2]; b = a; a is b True
is not a = [1,2]; b = [1,2]; a is not b True
[1,2] == [1,2] → True, but they are different objects → is returns False.
7. Membership Operators
Test if a value is in a sequence (list, string, tuple, etc.).
Operator Example Result
in ’a’ in ’apple’ True
not in 10 not in [1,2,3] True
Works with strings, lists, tuples, sets, dictionaries (checks keys).