Tutorials Python Python Operators
Ch 11 / 58
Python Beginner 10 min read Chapter 11 of 58

Python Operators

Operators are the symbols that tell Python what to do with values. From basic arithmetic to bitwise manipulation, Python has seven operator categories. This chapter covers every single one — with examples, comparison tables, and the complete precedence chart that determines the order Python evaluates complex expressions.

What you'll learn in this chapter
Arithmetic operators & augmented assignment
Comparison operators — ==, !=, <, >, <=, >=
Logical operators — and, or, not
Bitwise operators — &, |, ^, ~, <<, >>
Identity & membership operators — is, in
Full operator precedence table
Advertisement

Arithmetic Operators

Arithmetic operators perform mathematical calculations. Python provides seven of them. The / operator always returns a float in Python 3, while // performs floor division returning an integer. The ** exponentiation operator uses right-to-left associativity.

Python — arithmetic_operators.py
a, b = 17, 5

print(f"Addition        {a} + {b}  = {a + b}")   # 22
print(f"Subtraction     {a} - {b}  = {a - b}")   # 12
print(f"Multiplication  {a} * {b}  = {a * b}")   # 85
print(f"True Division   {a} / {b}  = {a / b}")   # 3.4  (always float)
print(f"Floor Division  {a} // {b} = {a // b}")  # 3    (rounds down)
print(f"Modulus         {a} % {b}  = {a % b}")   # 2    (remainder)
print(f"Exponentiation  {a} ** {b} = {a ** b}")  # 1419857

# Useful tricks
print(9 % 2)              # 1  → odd/even check: n%2==0 is even
print(-7 // 2)            # -4  → floor goes toward -∞
print(2 ** 3 ** 2)        # 512 → 2**(3**2) right-to-left
print(4 ** 0.5)           # 2.0 → square root via exponent
Operator Name Example Result
+ Addition 8 + 3 11
- Subtraction 8 - 3 5
* Multiplication 8 * 3 24
/ True Division 8 / 3 2.6666…
// Floor Division 8 // 3 2
% Modulus 8 % 3 2
** Exponentiation 2 ** 8 256

Assignment Operators

Assignment operators store values in variables. The basic = assigns a value. Augmented assignment operators (compound operators) combine an arithmetic or bitwise operation with assignment — shorthand that modifies a variable in-place, writing cleaner and faster code.

Python — assignment_operators.py
x = 10         # basic assignment

# Augmented assignment — each line modifies x in place
x += 5          # x = x + 5  → 15
x -= 3          # x = x - 3  → 12
x *= 2          # x = x * 2  → 24
x /= 4          # x = x / 4  → 6.0  (becomes float!)
x //= 2         # x = x // 2 → 3.0
x %= 2          # x = x % 2  → 1.0
x **= 4         # x = x ** 4 → 1.0
print(x)        # 1.0

# Bitwise augmented assignment
n = 0b1100     # 12 in binary
n &= 0b1010    # n = n & 0b1010 → 0b1000 = 8
n |= 0b0011    # n = n | 0b0011 → 0b1011 = 11
n ^= 0b0101    # n = n ^ 0b0101 → 0b1110 = 14
n <<= 1        # left shift → 28
n >>= 2        # right shift → 7
print(n)        # 7

# Walrus operator := (Python 3.8+) — assign AND use in one expression
data = [1, 2, 3, 4, 5]
if (n := len(data)) > 3:
    print(f"List is long: {n} items") # List is long: 5 items
x += n
Adds n to x in-place. Equivalent to x = x + n but more concise and readable.
x /= n
True division — result is always float. Use //= if you need an integer result.
:= walrus
Assigns and returns a value inside an expression. Useful in while loops and if conditions to avoid evaluating the same expression twice.
Advertisement
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Django & DRF FastAPI PostgreSQL Machine Learning Docker & AWS Real Projects AI Tools

Comparison Operators

Comparison operators compare two values and always return a bool — either True or False. They are the foundation of every if statement, loop condition, and filter. Python supports chained comparisons — a unique feature that reads like natural language mathematics.

Python — comparison_operators.py
a, b = 10, 20

print(a == b)    # False — equal to
print(a != b)    # True  — not equal to
print(a <  b)    # True  — less than
print(a >  b)    # False — greater than
print(a <= b)    # True  — less than or equal
print(a >= b)    # False — greater than or equal

# Chained comparisons — unique to Python!
x = 15
print(10 < x < 20)         # True  — reads like math!
print(1 <= x <= 10)         # False
print(5 < x == 15)          # True  — chains work left-to-right

# Comparing strings — lexicographic (Unicode order)
print("apple" < "banana")   # True  — 'a' < 'b'
print("Z" < "a")            # True  — uppercase < lowercase (ASCII)

# ⚠️ Never use == to compare floats directly
print(0.1 + 0.2 == 0.3)     # False — IEEE 754 quirk
import math
print(math.isclose(0.1+0.2, 0.3))  # True  — correct way
Chained comparisons 1 < x < 10 is valid Python and means 1 < x and x < 10. This is more readable than the Java/C equivalent x > 1 && x < 10.

Logical Operators

Logical operators combine boolean expressions. Python uses the English keywords and, or, and not instead of symbols like &&, ||, !. Python logical operators use short-circuit evaluation and return the actual operand value, not just True/False.

Python — logical_operators.py
# Basic logical operators
print(True  and True)    # True
print(True  and False)   # False
print(False or  True)    # True
print(False or  False)   # False
print(not True)           # False
print(not False)          # True

# Short-circuit evaluation
# 'and' stops at first False — second operand not evaluated
print(False and print("never"))  # False (print never called)
# 'or' stops at first True
print(True  or  print("never"))  # True  (print never called)

# Logical ops return the ACTUAL operand, not just bool
print(0    or  "default")  # "default"  — 0 is falsy, returns right side
print("hi" or  "default")  # "hi"       — "hi" is truthy, returns left side
print(5    and 10)         # 10         — both truthy, returns last
print(0    and 10)         # 0          — 0 is falsy, short-circuits

# Practical: default value pattern
name = ""
display = name or "Guest"
print(display)              # Guest (name is empty = falsy)

# Combined logical in if statement
age, has_id = 20, True
if age >= 18 and has_id:
    print("Entry allowed")   # Entry allowed
Operator Description Example Result
and True if both operands are truthy True and False False
or True if at least one operand is truthy False or True True
not Inverts the boolean value not True False

Bitwise Operators

Bitwise operators work directly on the binary (bit-level) representation of integers. They are essential for embedded systems, networking (IP masks), cryptography, permissions flags, and performance-critical code. Python applies them to integer values bit by bit.

Python — bitwise_operators.py
a = 0b1010   # 10 in decimal
b = 0b1100   # 12 in decimal

# AND — 1 only where BOTH bits are 1
print(bin(a & b))   # 0b1000 = 8

# OR — 1 where AT LEAST ONE bit is 1
print(bin(a | b))   # 0b1110 = 14

# XOR — 1 where bits are DIFFERENT
print(bin(a ^ b))   # 0b0110 = 6

# NOT — inverts all bits (adds 1 to negative)
print(~a)            # -11  (~n = -(n+1))

# LEFT SHIFT (<<) — multiply by 2^n
print(a << 1)       # 20   (10 × 2)
print(a << 2)       # 40   (10 × 4)

# RIGHT SHIFT (>>) — divide by 2^n (floor)
print(a >> 1)       # 5    (10 ÷ 2)
print(b >> 2)       # 3    (12 ÷ 4)

# Practical: check if number is even with bitwise AND
print(7 & 1)        # 1 → odd  (last bit is 1)
print(8 & 1)        # 0 → even (last bit is 0)

# Practical: swap two variables without temp (XOR trick)
x, y = 5, 9
x ^= y; y ^= x; x ^= y
print(x, y)       # 9 5 — swapped!
Operator Name Example Result Description
& AND 5 & 3 1 1 only where both bits = 1
| OR 5 | 3 7 1 where at least one bit = 1
^ XOR 5 ^ 3 6 1 where bits differ
~ NOT ~5 -6 Inverts all bits
<< Left Shift 5 << 1 10 Shift bits left (×2 per step)
>> Right Shift 5 >> 1 2 Shift bits right (÷2 per step)

Identity Operators — is, is not

Identity operators check whether two variables point to the same object in memory — not whether they have the same value. This is the critical difference between is and ==. Use is for checking None, and == for value equality.

Python — identity_operators.py
a = [1, 2, 3]
b = [1, 2, 3]   # same VALUE, different OBJECT
c = a             # c points to the SAME object as a

print(a == b)     # True  — same VALUE
print(a is b)    # False — different OBJECTS in memory
print(a is c)    # True  — same OBJECT
print(a is not b) # True

# Check memory identity with id()
print(id(a), id(b), id(c))
# a and c share the SAME id; b has a different id

# ✅ CORRECT: always use 'is' to test for None
result = None
if result is None:
    print("No result yet")     # No result yet

# ⚠️ Small integer caching (CPython implementation detail)
x = 256
y = 256
print(x is y)    # True  — CPython caches -5 to 256
x = 257
y = 257
print(x is y)    # False — outside cache range (usually)
is vs == — critical difference Never use if x == None. Always write if x is None. The == check calls __eq__() which can be overridden. is None is a guaranteed identity check and is the PEP 8 standard.

Membership Operators — in, not in

Membership operators test whether a value exists inside a sequence (string, list, tuple, set, dict). They return True or False. For sets and dict keys, membership testing is O(1). For lists and tuples, it is O(n).

Python — membership_operators.py
# String membership
print("Py"  in "Python")      # True
print("java" in "Python")    # False
print("on" not in "Python")  # False

# List membership  — O(n)
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits)     # True
print("grape"  in fruits)     # False

# Set membership  — O(1) fastest
valid_roles = {"admin", "editor", "viewer"}
print("admin" in valid_roles)  # True
print("guest" in valid_roles)  # False

# Dict membership  — checks KEYS
user = {"name": "Alice", "age": 25}
print("name" in user)          # True  (key check)
print("Alice" in user)         # False (not a key)
print("Alice" in user.values()) # True  (value check)

# Practical: input validation
role = "admin"
if role in valid_roles:
    print(f"Access granted for {role}")

Operator Precedence

Operator precedence determines the order Python evaluates operators in a complex expression. Higher precedence operators are evaluated first. When in doubt, use parentheses — they always have the highest precedence and make your intent explicit.

Python — precedence_examples.py
# Precedence in action — higher binds tighter
print(2 + 3 * 4)        # 14  — * before +
print((2 + 3) * 4)      # 20  — () overrides
print(2 ** 3 ** 2)      # 512 — ** right-to-left: 2**(3**2)
print(not True or True) # True — 'not' before 'or'
print(1 + 2 > 2 and 4 < 5) # True — arith → compare → logical
print(5 > 3 is True)    # True — comparison chains with 'is'
print(3 & 5 + 2)         # 1    — + before & (arith before bitwise)
Priority Operator(s) Description Associativity
1 (Highest) () Parentheses —
2 ** Exponentiation Right-to-left
3 +x -x ~x Unary plus, minus, bitwise NOT Right-to-left
4 * / // % Multiplication, division, floor div, modulus Left-to-right
5 + - Addition, subtraction Left-to-right
6 << >> Bitwise shift operators Left-to-right
7 & Bitwise AND Left-to-right
8 ^ Bitwise XOR Left-to-right
9 | Bitwise OR Left-to-right
10 == != < > <= >= is is not in not in Comparisons, identity, membership Left-to-right
11 not Logical NOT Right-to-left
12 and Logical AND Left-to-right
13 (Lowest) or Logical OR Left-to-right
Pro tip — use parentheses liberally Even experienced Python developers use parentheses in complex expressions rather than relying on memorised precedence. (a + b) * c is always clearer than relying on mental models. Code is read far more than it is written.

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice all the operator examples from this chapter directly in your browser with these free Python environments.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Test every operator example instantly.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • Python has 7 operator categories: arithmetic, assignment, comparison, logical, bitwise, identity, and membership.
  • Arithmetic: / always returns float; // floor-divides; ** is right-to-left; % gives remainder.
  • Augmented assignment (+=, -=, etc.) modifies variables in-place. The walrus operator := assigns inside expressions (Python 3.8+).
  • Comparison always returns bool. Python supports chained comparisons: 1 < x < 10. Never use == for float comparison.
  • Logical: and, or, not. Short-circuit evaluation — or/and return the actual operand, not just True/False.
  • Bitwise: &, |, ^, ~, <<, >> operate on binary representations. Shifts multiply/divide by powers of 2.
  • Identity: is/is not — checks object identity, not value. Always use is None, never == None.
  • Membership: in/not in — O(1) for sets/dicts; O(n) for lists. Use sets for large membership checks.
  • Precedence: () → ** → unary → * / // % → + - → shifts → bitwise → comparisons → not → and → or.
⚡
Free Resource
Download our Python Operators Cheat Sheet
All 7 operator types, full precedence table & bitwise reference — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

== is the equality operator — it calls the __eq__() method and checks whether two objects have the same value. is is the identity operator — it checks whether two variables point to the exact same object in memory (same id()). Two lists can have equal values but be different objects: [1,2] == [1,2] is True but [1,2] is [1,2] is False. Always use is None (not == None) and is True/is False when checking singletons.

✓ Answer

Short-circuit evaluation means Python stops evaluating a logical expression as soon as the result is determined, without evaluating the remaining operands. For and: if the first operand is falsy, Python returns it immediately without checking the second (since the result is already False). For or: if the first operand is truthy, Python returns it immediately without checking the second. This matters for performance and safety — the right side may have a function call or expression you only want to execute when needed:

# Safe division — right side only runs if x != 0
x = 0
print(x != 0 and 10 / x)   # False — no ZeroDivisionError!
✓ Answer

The walrus operator (:=), introduced in Python 3.8, is the assignment expression operator. It assigns a value to a variable and returns that value in a single expression. This avoids calling the same function or expression twice. Common use cases:

# while loop — read until empty
while chunk := read_data():
    process(chunk)

# if — assign and test in one line
if (n := len(my_list)) > 10:
    print(f"Too long: {n} items")
✓ Answer

Lists store items sequentially — to find an element, Python scans from the start until it finds it. In the worst case it checks every element: O(n) time complexity. Sets (and dict keys) are implemented as hash tables. Python computes the hash of the value being searched and jumps directly to the bucket where it would be stored — typically in O(1) constant time, regardless of the set's size. For 1 million items, a list check could take millions of steps; a set check takes one. This is why the pattern if x in my_set is dramatically faster than if x in my_list for large collections.

✓ Answer

Python evaluates this step-by-step following precedence rules (highest first):

  • Step 1 — Arithmetic: 4 + 1 → 5. Expression becomes: not 5 > 3 and 5 == 5
  • Step 2 — Comparison: 5 > 3 → True; 5 == 5 → True. Expression becomes: not True and True
  • Step 3 — not (highest logical): not True → False. Expression becomes: False and True
  • Step 4 — and: False and True → False
  • Result: False
MCQ 1 of 3
What is the result of 2 ** 3 ** 2 in Python?
MCQ 2 of 3
What does 0 or "hello" or "world" return in Python?
MCQ 3 of 3
What is the result of 0b1010 & 0b1100 in Python?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel