Summary: in this tutorial, you’ll learn how to use the Python pass
statement as a placeholder.
Introduction to the Python pass statement
Suppose that you have the following if...else
statement:
counter = 1 max = 10 if counter <= max: counter += 1 else: # implement later
Code language: Python (python)
In the else
clause, you haven’t got any code yet. But you’ll write code for this else
clause later.
In this case, if you run the code, you’ll get a syntax error (SyntaxError
).
This is where the Python pass
statement comes into play:
counter = 1 max = 10 if counter <= max: counter += 1 else: pass
Code language: Python (python)
The pass
statement is a statement that does nothing. It’s just a placeholder for the code that you’ll write in the future.
When you run the code that contains a pass
statement, the Python interpreter will treat the pass
statement as a single statement. As a result, it doesn’t issue a syntax error.
Technically, you can use the pass
statement in many statement in Python.
Let’s take some examples of using the pass
statement.
1) Using the Python pass statement with the if statement example
The following shows how to use the pass
statement with an if
statement:
if condition: pass
Code language: Python (python)
2) Using the Python pass statement with the for statement
This example shows how to use the pass
statement in a for
loop:
for i in range(1,100): pass
Code language: Python (python)
3) Using the Python pass statement with the while statement
The following example shows how to use the pass
statement with a while
loop:
while condition: pass
Code language: Python (python)
4) Using the Python pass statement with functions and classes
Later, you’ll learn how to define a function:
def fn(): pass
Code language: Python (python)
and a class:
class Stream: pass
Code language: Python (python)
In these examples, you use the pass
statement to mark the function and class empty.
Leave a Reply