Tip 18 Pass It

Pythonic Programming — by Dmitry Zinoviev (27 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Avoid range() in Loops | TOC | Try It 👉

★2.7, 3.4+ Some compound statements in Python (for example, class, for, while, if, and try) require that their body is not empty and contains at least one statement. Even if you do not want to provide that statement, you must. In C/C++/Java, one would use an empty statement — a block of two curly braces {}. Python does not use curly braces (at least not for this purpose). Instead, it uses indentation, and there is a problem with an empty statement defined through indentation — it is invisible, like this:

​ ​class​ EmptyClass:
​ ​# Is there an empty statement here? Can you see it?​

Python provides an equivalent of an empty statement called pass. You use pass when you must use a statement, but you do not care about it:

​ ​class​ EmptyClass:
​ ​pass​

You could use a string literal instead, something like “Do nothing here” — but that goes against The Zen of Python: “There should be one — and preferably only one — obvious way to do it.”

👈 Avoid range() in Loops | TOC | Try It 👉

Pythonic Programming by Dmitry Zinoviev can be purchased in other book formats directly from the Pragmatic Programmers. If you notice a code error or formatting mistake, please let us know here so that we can fix it.

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.