Python operators are special symbols that perform operations on variables and values. Here’s a comprehensive explanation of all Python operator types with examples:
Python Arithmetic Operators
Perform mathematical operations:
# Addition (+)
x = 5 + 3 # 8
# Subtraction (-)
y = 10 - 4 # 6
# Multiplication (*)
z = 7 * 2 # 14
# Division (/)
a = 15 / 4 # 3.75 (always returns float)
# Floor Division (//)
b = 15 // 4 # 3 (returns integer, discards remainder)
# Modulus (%)
c = 15 % 4 # 3 (remainder of division)
# Exponentiation (**)
d = 2 ** 3 # 8 (2 to the power of 3)
# Example with variables:
num1 = 10
num2 = 3
print(num1 + num2) # 13
print(num1 ** num2) # 1000
Comparison (Relational) Operators
Compare values and return True or False:
# Equal (==)
5 == 5 # True
5 == '5' # False
# Not Equal (!=)
10 != 20 # True
# Greater Than (>)
15 > 10 # True
# Less Than (<)
15 < 10 # False
# Greater Than or Equal (>=)
15 >= 15 # True
# Less Than or Equal (<=)
15 <= 10 # False
# Example:
age = 25
print(age >= 18) # True (eligible to vote)
Assignment Operators
Assign values to variables:
# Basic assignment (=)
x = 10
# Add and assign (+=)
x += 5 # equivalent to x = x + 5 → 15
# Subtract and assign (-=)
x -= 3 # 12
# Multiply and assign (*=)
x *= 2 # 24
# Divide and assign (/=)
x /= 4 # 6.0
# Modulus and assign (%=)
x %= 4 # 2.0
# Floor divide and assign (//=)
x //= 1 # 2.0
# Exponent and assign (**=)
x **= 3 # 8.0
# Walrus operator (:=) - Python 3.8+
if (n := len('hello')) > 4:
print(f"Length is {n}") # Length is 5
Python Logical Operators
Combine conditional statements:
# AND (both conditions must be True)
(5 > 3) and (10 < 20) # True
# OR (at least one condition must be True)
(5 > 3) or (10 > 20) # True
# NOT (reverse the result)
not(5 > 3) # False
# Example:
temperature = 25
is_summer = True
if temperature > 30 or (is_summer and temperature > 25):
print("It's hot!")
Python Identity Operators
Compare object memory locations:
x = [1, 2, 3]
y = [1, 2, 3]
z = x
# is (same object)
x is z # True
x is y # False (same content but different objects)
# is not (not the same object)
x is not y # True
# Example:
a = None
if a is None:
print("a is None")
Python Membership Operators
Test if a value exists in a sequence:
fruits = ['apple', 'banana', 'cherry']
# in
'banana' in fruits # True
'mango' in fruits # False
# not in
'mango' not in fruits # True
# Example:
username = 'admin'
if username in ['admin', 'root', 'superuser']:
print("Privileged access granted")
Python Bitwise Operators
Work on bits (binary operations):
a = 10 # 1010 in binary
b = 4 # 0100 in binary
# AND (&)
a & b # 0 (0000)
# OR (|)
a | b # 14 (1110)
# XOR (^)
a ^ b # 14 (1110)
# NOT (~)
~a # -11 (2's complement form)
# Left Shift (<<)
a << 2 # 40 (101000)
# Right Shift (>>)
a >> 2 # 2 (0010)
# Example:
flags = 0b1100 # 12 in decimal
mask = 0b1010 # 10 in decimal
result = flags & mask # 0b1000 (8 in decimal)
Ternary Operator (Conditional Expression)
Shortcut for if-else:
# Traditional if-else
if age >= 18:
status = "Adult"
else:
status = "Minor"
# Ternary equivalent
status = "Adult" if age >= 18 else "Minor"
# Example:
score = 85
result = "Pass" if score >= 60 else "Fail"
print(result) # Pass
Operator Precedence
Operators are evaluated in this order (top to bottom):
- Parentheses
()
- Exponentiation
**
- Bitwise NOT
~
, Unary+
and-
- Multiplication
*
, Division/
, Floor//
, Modulus%
- Addition
+
, Subtraction-
- Bitwise shifts
<<
,>>
- Bitwise AND
&
- Bitwise XOR
^
- Bitwise OR
|
- Comparison
==
,!=
,>
,>=
,<
,<=
- Identity
is
,is not
- Membership
in
,not in
- Logical NOT
not
- Logical AND
and
- Logical OR
or
# Example showing precedence
result = 5 + 3 * 2 ** 2 / 4 - 1 # Equivalent to 5 + ((3 * (2 ** 2)) / 4) - 1
print(result) # 7.0
Understanding these operators is fundamental to writing effective Python code. Each serves specific purposes and can be combined to create complex expressions and logic flows.