Tutorials Python Python pass Statement
Ch 18 / 58
Python Beginner 6 min read Chapter 18 of 58

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 you'll learn in this chapter
What pass is and why Python needs it
pass in loops, if/else, functions and classes
pass as a development stub / placeholder
Silently ignoring exceptions with pass
pass vs continue vs break — key differences
When to use pass and when to use alternatives
Advertisement

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.

Why Python needs pass Unlike languages with curly braces (Java, C, JavaScript) where an empty block {} is valid, Python uses indentation — an empty indented block after a colon causes IndentationError. pass is the solution.
Stub functions
Define a function signature before writing the body
Empty classes
Create a class shell to implement later
Silent exceptions
Catch and intentionally ignore errors
Empty branches
Placeholder for if/elif/else arms
No-op loops
Consume iterables without processing
Abstract base
Skeleton class for subclass completion

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 — Execution Flow Diagram
▶ Enter block
↓
pass ← does nothing
↓
execution falls through immediately
↓
Continue to next statement
↓
◼ Normal flow resumes
Python — pass_syntax.py
# 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.

Python — pass_in_loops.py
# 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
for x in items: pass
The loop iterates over all items — pass just ensures no IndentationError. Useful as a development stub.
pass ≠ continue
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.
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

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.

Python — pass_in_conditionals.py
# 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")
Silent exceptions — use with care 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.

Python — pass_in_functions.py
# 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.

Python — pass_in_classes.py
# 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
Custom exceptions with pass Creating custom exception classes with just 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
No
Yes — falls through
Yes — normal
continue Skips current iteration
No
No — skipped
Yes — next iter
break Exits loop immediately
Yes — exits
No — skipped
No — loop ends
Python — pass_vs_break_continue.py
# 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.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Test every pass statement example instantly.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • pass is 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, pass creates a loop that iterates but performs no action. It does not skip any code — execution falls through to whatever follows.
  • In conditionals, pass creates an empty branch. Common in try/except to silently ignore specific, expected exceptions.
  • In functions, pass creates stubs — function signatures you can call and test before writing the implementation.
  • In classes, pass creates empty classes. The most common real-world use is building a custom exception hierarchy (class MyError(Exception): pass).
  • pass vs continue: pass does nothing and falls through; continue skips remaining body code and jumps to the next iteration.
  • pass vs break: pass does nothing and the loop continues; break exits the loop immediately.
  • Always use the most specific exception type with except ... : pass — never except Exception: pass, which hides all errors.
⚡
Free Resource
Download our Python pass Statement Cheat Sheet
pass syntax, all use cases, pass vs continue vs break comparison & anti-patterns — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

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.

✓ Answer

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
✓ Answer

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'>
✓ Answer

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: pass is 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(...).
✓ Answer

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.

MCQ 1 of 3
What is the output of: for i in range(3): if i==1: pass; print(i, end=" ")?
MCQ 2 of 3
What does a function with pass as its only body statement return?
MCQ 3 of 3
Which statement does Python require so that an empty class body doesn't cause an error?

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