Lesson 20: Python pass statement

  • When you’re defining functions your code block will throw a syntax error if you don’t type a statement.
  • Above is valid for loops as well
  • And also for conditional statements (if)
Python syntactically requires that code blocks such as: if, for loop, while loop, function definition and class etc. are not empty.

Function : N/A

No new function will be introduced in this lesson.

Used Where?

Python’s pass statement is a nice quick fix that can be used as a placeholder not to get syntax errors.
For instance: 
  • As a placeholder when you want to run your code in an incomplete state and finish it later in functions, conditional statements or loops.
  • When processing exceptions after the <except> statement.

Syntax do(s)

1) pass is a statement that's used as a single word: pass

Syntax don't(s)

1) na

Example 1

>>> if 1==1:
>>>     pass

With the above code nothing will happen, however if you remove pass statement, the code would give a syntax error.

Tips

1- Commenting vs pass statement:

Python comments (starts with #) are intended for readers only and they never get compiled or executed.

However, Python pass comment actually gets executed, the result is Null and nothing happens but it does complete the syntax when needed.

2- pass statement might not make too much sense in the beginning but when you have multiple lines of codes, functions and classes, it can be very useful to do some debugging or test your code without having to remove sections and get syntax error.

Example 2

Loop example:

>>> for i in range(10):
>>>     pass

Again nothing happens but syntax error is avoided.

Advanced Concepts (Optional)

Although statement will be introduced later here is a quick example in advance to demonstrate the potential use of statement.

Example 3

Counting from end 

>>> def alti():
>>>     pass

Congratulations!!

If you’ve followed the lessons in order, this is the last lesson of the intermediate level. Congratulations for your courage, effort and consistency. You can continue with the Advanced  Python Lessons or Python Tutorials.