Pass. In Python we use the "pass" keyword (a statement) to indicate that nothing happens—the function, class or loop is empty. It is sometimes needed for correct syntax.
With pass, we indicate a "null" block. Pass can be placed on the same line, or on a separate line. Pass can be used to quickly add things that are unimplemented.
Method example. Here we use the "pass" statement on two methods. These methods do nothing. But they can be called in Python code.
Result Nothing happens when the pass methods are called. Pass can be used in other places in Python programs.
# This function does nothing.# ... It is empty.
def test(n): pass
# Pass can be on a separate line.
# Call our empty functions.
# We are done.
Class example. Sometimes we use the "pass" statement in a class. When we first add a class, we might not be ready to add its entire contents. Pass is helpful.
# An empty class.
class Box: pass
# A class with an empty method.
# Create empty class.
x = Box()
# Create class and call empty method.
b = Bird()
# Program is done.
If example. Here we use pass in an if-statement. If a method has a side effect, we sometimes might want to call it even if we do not do anything afterwards.
And With pass we can add "elif" clauses afterwards. This sometimes makes code clearer to read.
# This method has a side effect.# ... It prints a word.
def equals(name, value):
return name == value
name = "snake"# Use if-statement with a method that has a side effect.# ... Use pass to ignore contents of block.
if equals(name, "snake"):
While example. With a while-loop, we can use a "pass" statement. Sometimes we want to keep calling a method while a condition is true. With pass we can use an empty loop body.
# Print and return a random int.
result = random.randint(0, 5)
# Continue calling x while its value is at least 1.# ... Use no loop body.
while x() >= 1:
A summary. Python has a full-featured group of keywords. But it has no semicolons. So we must indicate an empty line with a special keyword. That is "pass."
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 28, 2021 (edit).