Python pass Statement
The pass statement is Python's null
operation — it does exactly nothing when executed. It exists because Python's grammar requires a
statement wherever a code block is expected, and sometimes you have no code to write yet. pass lets you create syntactically valid empty bodies for functions, classes,
loops, and conditionals — acting as a placeholder you'll fill in later. This chapter covers every use case
with clear diagrams and comparisons to break and continue.
What is the pass Statement?
pass is a null operation in Python
— when the interpreter executes pass, absolutely nothing happens. No value
is returned, no variable is changed, no action is taken. Execution simply continues with the next statement.
Python's syntax requires that every code block (after if, else, for, while, def, class, try, except, etc.) contains at least
one statement. When you don't have any meaningful code to put there yet, pass fills that requirement without doing anything.
{} is valid, Python uses indentation — an empty indented
block after a colon causes IndentationError. pass is the solution.
Syntax & Flow Diagram
pass is a single keyword statement — no arguments,
no return value, no side effects. It can appear anywhere a statement is expected. Here is the basic syntax and
a flow diagram showing that it truly does nothing to the program's execution path:
# pass is a single-keyword statement
pass # valid anywhere a statement is expected
# What happens when pass executes:
print("Before pass")
pass # nothing happens here
print("After pass") # runs immediately after
# Before pass
# After pass
# Why it's needed — without pass, SyntaxError!
# if True:
# ← IndentationError: expected an indented block
# With pass — syntactically valid
if True:
pass # valid empty block
# pass does not affect variables or state
x = 10
pass
print(x) # 10 — unchanged
pass in Loops
Using pass in a loop body creates a loop that
iterates over all elements but does nothing with them. This is useful for consuming an iterator, adding a TODO
stub, or as a no-op body while the loop condition or setup code is important. Remember: unlike continue, pass does not skip any
subsequent code in the body.
# pass as placeholder body in for loop
for i in range(5):
pass # TODO: process items later
# Loop still runs 5 times — pass just doesn't DO anything
print("Loop completed") # Loop completed
# pass as placeholder in while loop
count = 0
while count < 3:
count += 1 # update still runs!
pass # body placeholder
print(f"count = {count}") # count = 3
# pass does NOT skip remaining body (unlike continue)
for i in range(4):
if i == 2: pass # does nothing
print(i, end=" ") # ALL are printed
# 0 1 2 3 ← 2 is NOT skipped
# Consuming an iterator without processing
import itertools
counter = itertools.count(0)
for _ in range(100):
next(counter) # advance the iterator
pass # no processing needed
print(next(counter)) # 100
pass just ensures no IndentationError.
Useful as a development stub.pass falls through to remaining body code;
continue skips the rest of the body entirely. They look similar in a
one-liner but behave differently when more code follows.
pass in Conditionals
pass is frequently used in if/elif/else blocks as a placeholder for branches you haven't implemented yet,
or to explicitly do nothing for a specific condition while handling others. It also appears in try/except blocks to silently swallow exceptions.
# pass in an if block — placeholder
x = 10
if x > 0:
pass # handle positive case later
else:
print("Non-positive")
# Explicitly doing nothing for one branch
user_role = "viewer"
if user_role == "admin":
print("Full access")
elif user_role == "editor":
print("Edit access")
elif user_role == "viewer":
pass # viewers get nothing extra — intentional
else:
print("Unknown role")
# pass in try/except — silently ignore an exception
data = ["10", "abc", "30", "xyz", "50"]
numbers = []
for item in data:
try:
numbers.append(int(item))
except ValueError:
pass # silently skip non-integers
print(numbers) # [10, 30, 50]
# pass in match/case (Python 3.10+)
status = 200
match status:
case 200:
print("OK")
case 404:
pass # handle 404 later
case _:
print("Other")
except SomeError: pass swallows exceptions silently. This can hide bugs.
Always use the most specific exception type possible, and consider adding a comment explaining why
the error is intentionally ignored. Never use except Exception: pass — it
hides everything.
pass in Functions — Stubs & Interfaces
One of the most common uses of pass is creating
function stubs — function signatures defined upfront whose bodies will be implemented later.
This lets you plan your program's structure, write unit tests, and check that the overall design makes sense
before writing implementation code.
# Function stub — define signature, implement later
def load_data(filepath):
pass # TODO: read CSV file
def clean_data(df):
pass # TODO: handle nulls, outliers
def train_model(X, y):
pass # TODO: fit sklearn model
def evaluate(model, X_test, y_test):
pass # TODO: compute metrics
# You can call stubs — they return None silently
result = load_data("data.csv")
print(result) # None — pass returns nothing
# Abstract interface — force subclasses to implement
class Serialiser:
def serialise(self, data):
pass # subclasses must override this
def deserialise(self, raw):
pass
class JSONSerialiser(Serialiser):
def serialise(self, data):
import json
return json.dumps(data) # actual implementation
# Docstring + pass — document first, implement later
def send_email(to, subject, body):
"""Send an HTML email via SMTP.
Args:
to: recipient email address
subject: email subject line
body: HTML body content
Returns:
True on success, False on failure
"""
pass # TODO: integrate with email service
pass in Classes
pass in a class body creates an empty class — a
valid Python class with no attributes or methods. This is useful for creating marker classes, exception
hierarchies, placeholder models, and skeleton structures during top-down design.
# Empty class — fill in attributes and methods later
class User:
pass
# Empty classes are valid — you can instantiate them
u = User()
print(u) # <__main__.User object at 0x...>
# Dynamic attribute assignment still works
u.name = "Alice"
u.age = 25
print(u.name, u.age) # Alice 25
# Custom exception hierarchy with pass
class AppError(Exception):
pass # base exception for this app
class DatabaseError(AppError):
pass
class ValidationError(AppError):
pass
# Use the custom exceptions normally
try:
raise ValidationError("Email is required")
except ValidationError as e:
print(f"Validation failed: {e}")
# Validation failed: Email is required
# Marker / sentinel class
class Singleton:
pass # used as a unique sentinel value
MISSING = Singleton() # unique object — better than None as default
def get_value(d, key, default=MISSING):
if key in d:
return d[key]
if default is MISSING:
raise KeyError(key)
return default
pass is a very common Python
pattern. Your exceptions inherit all behaviour from Exception (or your
base class) while giving them a unique, meaningful type name that makes error handling clearer.
pass vs break vs continue — Clear Comparison
All three statements look similar — especially in one-liners — but they have completely different effects on program flow. This section shows the definitive comparison:
| Statement | Effect | Loop exits? | Body continues? | Next iteration? |
|---|---|---|---|---|
pass |
Does nothing — null op |
|
|
|
continue |
Skips current iteration |
|
|
|
break |
Exits loop immediately |
|
|
|
# All three with i==2 — spot the difference!
print("=== pass ===")
for i in range(5):
if i == 2: pass
print(i, end=" ")
# 0 1 2 3 4 ← ALL printed (pass does nothing)
print("\n=== continue ===")
for i in range(5):
if i == 2: continue
print(i, end=" ")
# 0 1 3 4 ← 2 SKIPPED
print("\n=== break ===")
for i in range(5):
if i == 2: break
print(i, end=" ")
# 0 1 ← STOPPED at 2
print("\n=== pass with more body code ===")
for i in range(4):
if i == 2: pass # pass — falls through!
print(f"i={i}", end=" ") # print still runs
# i=0 i=1 i=2 i=3
print("\n=== continue with more body code ===")
for i in range(4):
if i == 2: continue # continue — print SKIPPED for i=2
print(f"i={i}", end=" ")
# i=0 i=1 i=3
Practice Python Online — Free Compilers
Don't want to install anything yet? Practice all pass statement examples from this chapter directly in your browser with these free Python environments.
passis a null operation — it does absolutely nothing when executed. It exists to satisfy Python's syntax requirement that every code block contain at least one statement.- In loops,
passcreates a loop that iterates but performs no action. It does not skip any code — execution falls through to whatever follows. - In conditionals,
passcreates an empty branch. Common intry/exceptto silently ignore specific, expected exceptions. - In functions,
passcreates stubs — function signatures you can call and test before writing the implementation. - In classes,
passcreates empty classes. The most common real-world use is building a custom exception hierarchy (class MyError(Exception): pass). - pass vs continue:
passdoes nothing and falls through;continueskips remaining body code and jumps to the next iteration. - pass vs break:
passdoes nothing and the loop continues;breakexits the loop immediately. - Always use the most specific exception type with
except ... : pass— neverexcept Exception: pass, which hides all errors.
Python uses indentation to define code blocks instead of curly braces. When a statement like if, def, class, or for is followed by a
colon (:), Python expects an indented block of at least one
statement on the next line.
If you leave the block completely empty — just pressing Enter — Python raises
an IndentationError: expected an indented block. pass is the solution: it satisfies the syntax requirement while doing
absolutely nothing at runtime. Languages with curly braces use {}
for empty blocks; Python uses pass.
pass is a null operation — it does nothing and
execution falls through to any code that follows it in the same loop body. continue actively skips all remaining code in the
current iteration and immediately starts the next one.
for i in range(3):
if i == 1: pass # does nothing
print(i) # 0 1 2 ← all printed
for i in range(3):
if i == 1: continue # skips print below
print(i) # 0 2 ← 1 skipped
A function with only pass in its body returns None — the same as any function without an explicit return statement. When Python reaches the end of a function body
(including an empty body with pass), it implicitly returns None.
def stub():
pass
result = stub()
print(result) # None
print(type(result)) # <class 'NoneType'>
except Exception: pass silently catches every exception
— including TypeError, AttributeError, MemoryError, and
even programming errors like NameError. This hides bugs completely
— your program might be broken in fundamental ways but shows no error at all, making debugging nearly
impossible.
- Always catch the most specific exception:
except ValueError: passis fine if you genuinely expect and want to ignore conversion errors. - Add a comment explaining why the error is being ignored.
- Consider logging the error even if you don't re-raise it:
except IOError: logging.warning(...).
Creating custom exception hierarchies for a project. By defining empty exception
classes that inherit from Exception or a common base class, you
create named exception types that make try/except blocks more
expressive and specific:
class AppError(Exception): pass
class DatabaseError(AppError): pass
class NetworkError(AppError): pass
try:
raise DatabaseError("Connection lost")
except DatabaseError as e:
print(f"DB error: {e}")
The classes inherit all of Exception's
behaviour (message, args, traceback) while giving errors a meaningful, specific type name.
for i in range(3): if i==1: pass; print(i, end=" ")?pass as its only body
statement return?class body doesn't cause an error?
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.