Python pass Statement
1Python pass: overview
pass is a statement that does nothing; it exists because Python blocks cannot be empty, so you use it to hold the place of code you haven't written yet or don't need.
Before this lesson: Python Syntax, Python if, elif and else
2Python pass: diagram
3Python pass: explained step by step
Python marks the inside of a block (after if, else, for, def, class, try, except and so on) with indentation, and a line that ends in a colon is a promise: "an indented block follows". That block must contain at least one statement. Usually that's no problem, but while you're sketching a program you often know a block will be needed before you know what goes in it.
pass is the answer. It is a complete statement that does nothing at all: Python reads it, shrugs, and moves on. Its only job is to fill a spot where the grammar demands a statement.
temperature = 22
if temperature > 30:
pass # TODO: decide what to do on hot days
else:
print("Nice weather")
print("Done")Why a block cannot be empty
You might think a comment is enough to mark an empty block. It isn't. Python throws comments away before it looks at the structure of your code, so a block that holds only a comment is, to Python, a block with nothing in it. The result is an IndentationError with a message like expected an indented block after 'if' statement on line 2 (the wording changes with the kind of block: function definition, class definition, and so on). Put pass under the comment and the error disappears, and the comment can then explain why the pass is there.
Placeholders for functions and classes
Two more places where you'll meet pass constantly. A function (made with def) is a named block of code that runs when you call it by writing its name followed by brackets. A class (made with class) is a blueprint for creating objects. You'll learn both properly in later lessons. For now all you need to know is that each one needs a body, and pass lets you declare them first and fill them in later.
def send_welcome_email():
pass # to be written later
class Invoice:
pass # an empty blueprint is allowed too
print(send_welcome_email())
print("Program still runs")Calling the empty function works and gives back None, Python's value for "nothing". Because nothing crashes, you can run the whole program even while some parts are still unfinished.
pass, ... or a comment?
These three get mixed up, so here is the difference:
passis a statement that does nothing. It says "this block is empty on purpose" and works anywhere a block is needed....(three dots, called Ellipsis) is a real value written on its own line. It also fills a block, and many people use it to mean "I still have to write this", especially in function stubs.- A comment is not a statement, so it can never fill a block by itself. It is perfect next to a
passor...to explain it.
def load_settings():
...
def save_settings():
pass
print(load_settings())
print(save_settings())pass vs continue
Beginners sometimes expect pass to skip something. It doesn't: it does nothing, and execution simply carries on with the next line. continue is the statement that jumps ahead. This example uses a for loop, which repeats its indented block once for every item in the list (loops get their own lesson soon):
for number in [1, 2, 3, 4]:
if number % 2 == 0:
pass # does nothing, so the next line still runs
print("pass loop:", number)
for number in [1, 2, 3, 4]:
if number % 2 == 0:
continue # skips the rest of this round
print("continue loop:", number)except SomeError: pass is risky
The last place pass turns up is after except. A try / except pair lets a program survive a line that fails: the block under except ValueError: runs when a ValueError happens, instead of the program crashing. Putting pass there means "ignore this error".
data = ["12", "7", "abc", "30"]
total = 0
for text in data:
try:
total += int(text)
except ValueError:
pass # silently ignore anything that isn't a number
print("Total:", total)The program prints a total, but nothing tells you that "abc" was thrown away. An error is Python telling you something is wrong; swallowing it means you never find out, and the result just looks plausible while being wrong. A bare except: pass is worse still, because it hides every error, even a typo in your own code. If you do choose to ignore an error, name the specific error type, keep the try block tiny, and add a comment saying why that's safe. Better still, count or report what you skipped.
A stub-first workflow
pass makes a handy way of working possible. First write the skeleton of the whole program, with every function and branch as a placeholder, and run it to check that the structure holds together. Then fill in one piece at a time, replacing a pass with real code and running again after each step. You always have a program that runs, and you can see exactly how much is left. Just search for leftover pass lines before you call something finished.
Quick reference: Python pass
- Python break vs continue vs pass: Differences — `break` stops the whole loop, `continue` skips the rest of the current iteration and moves to the next one, a…
4Python pass: syntax
if condition:
pass # placeholder: does nothing
def name():
pass # empty function
class Name:
pass # empty class
try:
risky_step()
except SomeError:
pass # ignore this error on purpose (use with care)
... # Ellipsis: another way to write "to do"
5Python pass: run the example
Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.
def send_report():
pass # TODO: build the report later
class Student:
pass # TODO: add name and grades later
orders = ["pen", "book", "lamp", "book"]
packed = 0
for order in orders:
if order == "book":
pass # TODO: books need special wrapping
else:
packed += 1
print("Report result:", send_report())
print("Packed:", packed)
print("Student type:", type(Student()).__name__)Expected outputReport result: None
Packed: 2
Student type: Student
7Python pass: how the example works
Hover or tap a step to highlight its lines in the example above.
- Line 1-2
defcreates a function namedsend_report. Its body is justpass, so nothing runs yet; Python only needs the body to exist. - Line 4-5A class is a blueprint for objects. An empty class is allowed, again thanks to
pass. - Line 7-8A list of orders and a counter that starts at 0.
- Line 9-13The loop looks at each order. For
"book"theifblock is onlypass: nothing happens and nothing is counted. Every other order goes to theelsebranch and adds 1 topacked, so the pen and the lamp give 2. - Line 15Calling
send_report()runs itspassbody, which does nothing. A function that never returns a value gives backNone, which is what gets printed. - Line 16
packedended at 2, because both books were skipped by the placeholder branch. - Line 17
Student()builds an object from the empty class, andtype(...).__name__shows the name of its class.
8Python pass: common mistakes
Using only a comment as a block body
✗ Wrong
age = 16
if age >= 18:
# allow entry
print("Checked")✓ Right
age = 16
if age >= 18:
pass # allow entry: to be written
print("Checked")A comment is not a statement, so Python sees an empty block. Add pass (keep the comment if you like) so the block has something in it.
Leaving pass behind and forgetting to fill it in
✗ Wrong
def make_greeting(name):
pass
print(make_greeting("Asha"))✓ Right
def make_greeting(name):
return "Hello, " + name
print(make_greeting("Asha"))pass is a placeholder, not a finished piece of code. A function whose body is only pass gives back None. Once you're ready, write the real body; return hands the result back to the caller.
Hiding every error with except: pass
✗ Wrong
prices = ["4.50", "3.50", "oops"]
total = 0
for p in prices:
try:
total += float(p)
except:
pass
print(total)✓ Right
prices = ["4.50", "3.50", "oops"]
total = 0
for p in prices:
try:
total += float(p)
except ValueError:
print("Skipped:", p)
print(total)A bare except: catches everything and pass throws the evidence away. Catch the specific error you expect, and report or count what you skip.
Expecting pass to skip the rest of the loop body
✗ Wrong
for n in [1, 2, 3, 4]:
if n == 3:
pass
print(n)✓ Right
for n in [1, 2, 3, 4]:
if n == 3:
continue
print(n)pass does nothing and the loop carries on with the next line. To skip the rest of the current round, use continue.
9Python pass: exercises
Write your answer, then press Check. The checks run in your browser.
1. Declare two placeholders
Write code Easy ✓ CompletedYou're planning a small shop program. Declare two empty placeholders, each with pass as its body:
- a function named
send_receipt: writedef send_receipt():and indent apassline under it - a class named
Customer: writeclass Customer:and indent apassline under it
The program must still run to the end. The print line is already there to prove it.
# 1. a function called send_receipt whose body is just pass
# 2. a class called Customer whose body is just pass
print("Stubs declared")def send_receipt():
pass
class Customer:
pass
print("Stubs declared")
2. Predict pass and continue
Predict the output Medium ✓ CompletedRead the code and type exactly what it will print. Decide for each number which branch runs and whether the print line is reached. Then press Check to run it and compare.
for n in range(1, 6):
if n == 2:
pass
elif n == 4:
continue
print(n)
print("end")pass does nothing, so the loop still reaches print(n). Only continue jumps over it. Which numbers hit continue?1
2
3
5
end
2 more exercises → 5 more examples
Questions learners ask
What does pass do in Python?
Nothing at all. It is a statement that exists only to fill a spot where Python requires one, such as the body of an if, a loop, a function or a class. It lets you write the outline of a program now and fill in the details later.
What is the difference between pass and continue?
pass does nothing and the program carries on with the next line. continue is used inside a loop: it jumps straight to the next round and skips whatever is left in the loop body. Use pass as a placeholder and continue to skip work.
Is it bad to use except: pass?
It is risky, because it throws away errors so you never find out that something failed. If you must ignore an error, catch the specific type (for example except ValueError:), keep the try block small and comment why it is safe. Logging, printing or counting the problem is usually better than silence.
Further reading
10Next lesson
Up nextPython match StatementA match statement compares one value against a series of patterns, runs the first case that fits, and can pull pieces o…Related:
Python if, elif and elsePython FunctionsPython Exceptions: try, except, else and finally
← Python Truthy and Falsy Values · All Control Flow lessons · Practise in the IDE