What Are Operators?
An operator is a special symbol that performs an operation on one or more values (called operands). For example, in 3 + 4, the + is the operator and 3 and 4 are the operands. The result is 7.
Python groups operators into seven categories:
- Arithmetic: mathematical calculations (
+,-,*,/, etc.) - Comparison: compare two values and return a boolean (
==,!=,>,<, etc.) - Logical: combine boolean expressions (
and,or,not) - Assignment: assign values to variables (
=,+=,-=, etc.) - Bitwise: operate on binary representations (
&,|,^,~,<<,>>) - Identity: test object identity (
is,is not) - Membership: test membership in a collection (
in,not in)
Arithmetic Operators
Arithmetic operators perform mathematical operations. They work on numbers (int and float), and some also work on strings and lists (concatenation/repetition).
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 3 | 10 |
- | Subtraction | 7 - 3 | 4 |
* | Multiplication | 7 * 3 | 21 |
/ | Division (true) | 7 / 3 | 2.333... |
// | Floor Division | 7 // 3 | 2 |
% | Modulo (remainder) | 7 % 3 | 1 |
** | Exponentiation | 2 ** 8 | 256 |
- | Unary negation | -5 | -5 |
a, b = 17, 5
print(f"{a} + {b} = {a + b}") # 22
print(f"{a} - {b} = {a - b}") # 12
print(f"{a} * {b} = {a * b}") # 85
print(f"{a} / {b} = {a / b}") # 3.4
print(f"{a} // {b} = {a // b}") # 3 (floor division)
print(f"{a} % {b} = {a % b}") # 2 (remainder)
print(f"{a} ** {b} = {a ** b}") # 1419857 (17^5)
# Division always returns float in Python 3
print(10 / 2) # 5.0 (float, even if evenly divisible)
print(10 // 2) # 5 (int)
# Negative floor division: rounds towards negative infinity
print(-17 // 5) # -4 (not -3!)
print(-17 % 5) # 3 (result has same sign as divisor)
# String and list operators using + and *
print("Hello" + " " + "World") # Hello World
print("Ha" * 3) # HaHaHa
print([1, 2] + [3, 4]) # [1, 2, 3, 4]
print([0] * 5) # [0, 0, 0, 0, 0]
The modulo operator is incredibly useful: check if a number is even (n % 2 == 0), check divisibility (n % 3 == 0), wrap around a range (clock arithmetic: hour % 24), or extract the last digit (n % 10).
Comparison Operators
Comparison operators compare two values and always return a boolean (True or False). They are the foundation of all conditional logic.
x, y = 10, 20
print(x == y) # False β equal to
print(x != y) # True β not equal to
print(x > y) # False β greater than
print(x < y) # True β less than
print(x >= y) # False β greater than or equal
print(x <= y) # True β less than or equal
# Comparison works on strings too (lexicographic order)
print("apple" < "banana") # True (a < b alphabetically)
print("apple" == "Apple") # False (case-sensitive!)
print("z" > "a") # True
# Chained comparisons β very Pythonic!
age = 25
print(18 <= age < 65) # True β equivalent to (18 <= age) and (age < 65)
print(0 < 5 < 10 < 100) # True
score = 75
grade = "B" if 70 <= score < 80 else "Other"
print(grade) # B
= is the assignment operator. == is the equality comparison operator. Writing if x = 5: causes a SyntaxError. You must write if x == 5:. This is one of the most common mistakes for beginners coming from math or other languages.
Logical Operators
Logical operators combine boolean expressions. Python uses English words (and, or, not) rather than symbols (&&, ||, !) like most other languages.
| Operator | Description | Returns True when |
|---|---|---|
and | Logical AND | Both operands are truthy |
or | Logical OR | At least one operand is truthy |
not | Logical NOT | Operand is falsy |
# and β both must be True
print(True and True) # True
print(True and False) # False
print(False and True) # False
print(False and False) # False
# or β at least one must be True
print(True or True) # True
print(True or False) # True
print(False or True) # True
print(False or False) # False
# not β reverses the boolean value
print(not True) # False
print(not False) # True
# Practical usage
age = 22
has_id = True
is_sober = True
can_enter = age >= 18 and has_id and is_sober
print(can_enter) # True
# Short-circuit evaluation
# 'and': if first is False, second is never evaluated
# 'or': if first is True, second is never evaluated
x = 0
result = x != 0 and (10 / x > 2) # Safe! 10/x never runs
print(result) # False
# Logical operators work on non-boolean values too
# 'and' returns first falsy value, or last value if all truthy
print(0 and "hello") # 0 (0 is falsy, stops here)
print(5 and "hello") # hello (5 is truthy, returns second)
print("" and "hello") # "" ("" is falsy)
# 'or' returns first truthy value, or last value if all falsy
print(0 or "hello") # hello (0 is falsy, moves on)
print(5 or "hello") # 5 (5 is truthy, stops here)
print("" or 0 or None) # None (all falsy, returns last)
# Practical: default values using 'or'
username = ""
display_name = username or "Anonymous"
print(display_name) # Anonymous
Assignment Operators
Assignment operators assign values to variables. The augmented assignment operators combine an arithmetic operation with assignment, providing a concise shorthand.
score = 100 # Basic assignment
score += 50 # score = score + 50 β 150
score -= 30 # score = score - 30 β 120
score *= 2 # score = score * 2 β 240
score //= 7 # score = score // 7 β 34
score **= 2 # score = score ** 2 β 1156
score %= 100 # score = score % 100 β 56
print(score) # 56
# Walrus operator := (Python 3.8+) β assign and return at once
import re
data = "Temperature: 98.6"
if (match := re.search(r'\d+\.?\d*', data)):
print(f"Found: {match.group()}") # Found: 98.6
# Another walrus example: avoid calling a function twice
numbers = [1, 3, 5, 7, 9, 11]
if (n := len(numbers)) > 5:
print(f"List has {n} items β too long!") # List has 6 items β too long!
Bitwise Operators
Bitwise operators work on integers at the binary level, manipulating individual bits. They are commonly used in systems programming, cryptography, image processing, and working with hardware flags.
a = 0b1010 # 10 in decimal
b = 0b1100 # 12 in decimal
# AND: 1 if both bits are 1
print(bin(a & b)) # 0b1000 β 8
# OR: 1 if either bit is 1
print(bin(a | b)) # 0b1110 β 14
# XOR: 1 if bits are different
print(bin(a ^ b)) # 0b0110 β 6
# NOT: flip all bits (returns -(n+1))
print(~a) # -11
# Left shift: shift bits left (multiply by 2^n)
print(a << 1) # 20 (10 * 2)
print(a << 2) # 40 (10 * 4)
# Right shift: shift bits right (integer divide by 2^n)
print(a >> 1) # 5 (10 // 2)
# Practical: check if a number is even using bitwise AND
def is_even(n):
return n & 1 == 0
print(is_even(10)) # True
print(is_even(7)) # False
# Practical: flags using bitwise OR
READ = 0b001 # 1
WRITE = 0b010 # 2
EXECUTE = 0b100 # 4
user_permissions = READ | WRITE # 0b011 = 3
print(bool(user_permissions & READ)) # True β user can read
print(bool(user_permissions & EXECUTE)) # False β user cannot execute
Identity Operators: is and is not
Identity operators check whether two variables refer to the exact same object in memory, not just whether they have equal values. This is a subtle but important distinction.
# 'is' checks identity (same memory location)
# '==' checks equality (same value)
a = [1, 2, 3]
b = [1, 2, 3]
c = a # c points to the SAME object as a
print(a == b) # True β same values
print(a is b) # False β different objects in memory
print(a is c) # True β same object!
print(id(a)) # e.g. 140234567890 (memory address)
print(id(b)) # different address
print(id(c)) # same as id(a)
# Modifying c changes a too (they're the same object)
c.append(4)
print(a) # [1, 2, 3, 4] β a was changed through c!
# Use 'is None' to check for None (not ==)
value = None
print(value is None) # True β correct, Pythonic way
print(value is not None) # False
# Small integer caching
x = 256
y = 256
print(x is y) # True β Python caches integers -5 to 256
x = 1000
y = 1000
print(x is y) # False β not cached (implementation detail)
# Strings: interning
s1 = "hello"
s2 = "hello"
print(s1 is s2) # True β Python interns short strings (don't rely on this!)
# Best practice: use 'is' only for None, True, False
# Use '==' for everything else
Never write if x is 5: or if name is "Alice":. This compares object identity, not value, and will behave unpredictably due to Python's caching rules. Reserve is exclusively for is None, is True, and is False.
Membership Operators: in and not in
Membership operators test whether a value exists inside a collection (string, list, tuple, set, dictionary, etc.). They return a boolean.
# Membership in strings
sentence = "The quick brown fox"
print("fox" in sentence) # True
print("cat" in sentence) # False
print("cat" not in sentence) # True
print("quick" in sentence) # True
print("Quick" in sentence) # False (case-sensitive)
# Membership in lists
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # True
print("mango" in fruits) # False
# Membership in tuples
vowels = ('a', 'e', 'i', 'o', 'u')
print('e' in vowels) # True
print('y' in vowels) # False
# Membership in sets (fastest lookup!)
allowed_users = {"alice", "bob", "carol"}
username = "alice"
print(username in allowed_users) # True
# Membership in dictionary keys
config = {"host": "localhost", "port": 5432}
print("host" in config) # True
print("localhost" in config) # False β checks KEYS, not values
print("localhost" in config.values()) # True β explicitly check values
# Practical: validate user input
VALID_COLORS = {"red", "green", "blue", "yellow", "purple"}
color = input("Enter a color: ") if False else "red" # example
if color.lower() in VALID_COLORS:
print(f"'{color}' is a valid color")
else:
print(f"'{color}' is not recognized")
Checking membership in a list is O(n) β it scans every element. Checking in a set is O(1) β nearly instant regardless of size. When you need to repeatedly check membership in a large collection, convert it to a set first.
Operator Precedence
When an expression has multiple operators, Python evaluates them in a specific order called operator precedence β similar to the PEMDAS/BODMAS rules in mathematics. Higher precedence operators are evaluated first.
| Precedence | Operator(s) | Description |
|---|---|---|
| 1 (highest) | () | Parentheses (grouping) |
| 2 | ** | Exponentiation |
| 3 | +x, -x, ~x | Unary positive, negative, bitwise NOT |
| 4 | *, /, //, % | Multiplication, division, modulo |
| 5 | +, - | Addition, subtraction |
| 6 | <<, >> | Bitwise shifts |
| 7 | & | Bitwise AND |
| 8 | ^ | Bitwise XOR |
| 9 | | | Bitwise OR |
| 10 | ==, !=, <, >, <=, >=, is, in | Comparisons, identity, membership |
| 11 | not | Logical NOT |
| 12 | and | Logical AND |
| 13 (lowest) | or | Logical OR |
# Precedence in action
print(2 + 3 * 4) # 14 β * before +
print((2 + 3) * 4) # 20 β () overrides
print(2 ** 3 ** 2) # 512 β ** is RIGHT-associative: 2 ** (3 ** 2) = 2 ** 9
print((2 ** 3) ** 2) # 64 β forced left: (8) ** 2
print(10 - 3 - 2) # 5 β left-to-right: (10 - 3) - 2
print(100 / 10 * 2) # 20.0 β left-to-right: (100 / 10) * 2
# Comparison before logical operators
age = 25
income = 50000
print(age > 18 and income > 30000) # True and True β True
# Evaluated as: (age > 18) and (income > 30000)
# not has lower precedence than comparison
print(not 5 > 3) # False β not (5 > 3) β not True β False
print(not 5 < 3) # True β not (5 < 3) β not False β True
# Complex expression β parentheses for clarity
x = 4
result = x ** 2 + 2 * x - 1 # 16 + 8 - 1 = 23
print(result)
# Same result, explicit order:
result = (x ** 2) + (2 * x) - 1
print(result)
You don't need to memorize the full precedence table. When an expression is complex, use parentheses to make the order explicit. This improves readability and prevents subtle bugs. Code that is clearly correct beats code that requires mental precedence lookups every time.
ποΈ Practical Exercise
Write a Python program that:
- Uses arithmetic operators to compute the area of a circle (radius = 7) and the volume of a cylinder (radius = 5, height = 12). Use
3.14159for pi. - Uses comparison operators to check: is the circle's area larger than the cylinder's volume?
- Uses logical operators to check: is the radius of the cylinder between 3 and 8 (inclusive) AND is the height greater than 10?
- Uses membership to check if the string
"Python"contains both"Py"and"on"using a single expression withand.
π₯ Challenge Exercise
Write a function evaluate_loan(income, credit_score, debt, years_employed) that uses only operators (no if/else allowed) to compute an approval boolean. Rules: income must exceed 30000 AND credit_score must be at least 650 AND (debt / income) must be less than 0.4 AND years_employed must be at least 2. Return the single boolean result. Then test it with at least 4 different combinations of inputs that produce different outcomes.
Interview Questions on Operators
- What is the difference between
/and//in Python 3? - What does the
%(modulo) operator return? What is it used for? - What is the difference between
==andisin Python? - Explain short-circuit evaluation in Python's
andandoroperators. - What does
notdo to non-boolean values? What doesnot ""return? - What is the walrus operator
:=and when was it introduced? - Why is checking membership in a set faster than in a list?
- What does
**do? Is it left or right associative? What is2 ** 3 ** 2?
π Summary
- Python has 7 operator categories: arithmetic, comparison, logical, assignment, bitwise, identity, and membership.
- The
/operator always returnsfloat; use//for integer (floor) division. - Comparison operators return booleans; Python supports chained comparisons like
0 < x < 10. - Logical operators (
and,or,not) use short-circuit evaluation and return one of their operands (not necessarily a boolean). - Use
is/is notonly forNone,True, andFalseβ use==for value comparisons. - Use
in/not into check membership; sets offer O(1) membership testing. - Operator precedence follows mathematical conventions; parentheses always override.
- The walrus operator
:=(Python 3.8+) assigns and returns a value in a single expression.
Related Topics
Frequently Asked Questions
and returns the first falsy value, or the last value if all are truthy: 5 and "hello" returns "hello". or returns the first truthy value, or the last value if all are falsy: 0 or "default" returns "default". This is called "short-circuit evaluation" and is widely used to set default values.
Right-associative. 2 ** 3 ** 2 is evaluated as 2 ** (3 ** 2) = 2 ** 9 = 512. This differs from most other operators which are left-to-right. If you want left-to-right, use parentheses: (2 ** 3) ** 2 = 64.
and is a logical operator that works with any truthy/falsy values, uses short-circuit evaluation, and returns one of its operands. & is a bitwise operator that works at the binary level on integers, evaluates both sides always, and returns an integer. For boolean logic, always use and. Use & only for binary/bit manipulation.
key in dict checks if a key exists (this is O(1) for dicts). To check values, use value in dict.values() (this is O(n)). To check for a key-value pair, use (key, value) in dict.items(). For most use cases, you're checking for a key, not a value.
Python was designed to be highly readable β almost like pseudocode. Using English words for logical operators makes code read more like a natural sentence: if age > 18 and has_id: vs if age > 18 && has_id:. This is part of Python's philosophy that "readability counts."