Do you know why Python has a pass statement?
Python Video Tutorial column introduces why Python needs a pass statement.
Regarding the pass
statement in Python, it seems simple (only 4 letters), even a beginner without any programming experience can Learn how to use it quickly.
The introduction of the official document is very simple. The following three examples can let us quickly understand how to use it:

To put it simply, pass is a null operation. When the interpreter executes it, it does nothing except check whether the syntax is legal and skips it.
Compared with non-empty operations such as return, break, continue and yield, the biggest difference is that it does not change the execution order of the program. It is like a comment we write, except that it occupies a line of code and does not have any impact on the scope in which it is located.
However, if you have a foundation in other languages, you may be curious: Why does Python have such a unique pass statement, but other languages do not?
Why is Python designed like this?
Is it to solve the common problems faced by most programming languages, or is it a new feature created because it has its own new discoveries?
In other words: Why does Python have the pass statement, what problems does it solve (benefits), and what problems (disadvantages) will it cause without it?
Next, this article will analyze from two dimensions.
1. To people: As a space placeholder
I regard it as a concise and comprehensive way of commenting, which is equivalent to saying "Reserve a place here first, and then come back later" Fill in the specific code to implement ".
For example, in a multi-layered if-elif-else structure, we can write the judgment conditions first, then write pass in the corresponding block, and then slowly improve it later.
For example, in the example given above, we can first write the class/function name and its input parameters, then skip (pass) the main code, and then fill it in slowly later.
pass is easy to write, and because it is a keyword, the IDE will give you conspicuous color distinctions, so it is more convenient than writing comments.
pass As a space placeholder, it mainly facilitates us to conceive the local code structure and has a certain auxiliary reminder effect.
However, as a way of commenting, it is too thin and inferior to writing "# todo: xxxx". The latter will also be highlighted in color by the IDE and has a clearer meaning. Although simple to write, it also introduces a seemingly redundant keyword pass.
So, from the perspective of space placeholders, pass is not a necessary design element in programming languages.
With it, we can express the semantics of "there is something here, but skip it for now", but without it, it can be replaced by annotation content.
2. For the machine: For the sake of grammatical integrity
For the usage of the previous item, the position where pass appears in the code is theoretically unrestricted.
However, when we use pass most often, it is basically on the line next to the colon, and there is only this one statement in the indented code block at this level. (See the previous three examples. For convenience, we only take the empty function as an example)
We can imagine what would happen if we did not write it?
The answer is that an indentation error will be reported: IndentationError: expected an indented block
# 将函数体的 pass 去除,会报错def func():func()复制代码
Because Python uses indentation to divide code blocks (for the reason, please refer to "Why Python Use indentation to divide code blocks?》), and the colon marks the appearance of a new indented code block, so this example will report a missing indented code block.
What if we use the comments mentioned above instead?
# 将函数体的 pass 换成注释def func(): # todo:此处有东西,以后补上func()复制代码
Writing like this will also report an error: IndentationError: expected an indented block
The reason is that the comment is not a valid grammatical content and will be ignored by the Python interpreter ( ignore), unlike the pass statement which is "valid syntax content, but skipped".
In other words, the indented code block must contain grammatically meaningful content. The following examples are valid:
def func(): """这是一个字符串"""def func2(): 123456复制代码
Python When defining a function, it must include the function body, that is It contains both declaration and definition semantics. It cannot be like some languages that can only use the declaration semantics, which is written as void test();
.
However, since Python does not use curly braces, it cannot directly define an empty function like some languages, which is written as void test(){}
.
Based on the above analysis, Python must have a legal function body when defining an empty function, so a pass statement is designed to represent a no-op. It is intended to complete the syntax and, along with the colon, is equivalent to an empty pair of braces in other languages.
From the perspective of grammatical integrity, it is a necessary design element. If it is not available, it must be replaced with a similar empty statement or special symbol.
For humans, pass can mean "temporarily skip". As a temporary placeholder, it will eventually be replaced by the actual code implementation; for machines, it can mean "skip directly." ” is only used to complete the grammatical logic and will not be replaced by other codes.
Other languages do not have a special statement or symbol to represent this kind of placeholder (that is, the semantics are lacking), but they do not need to bother to design a keyword to complete the grammatical integrity ( i.e. grammatically complete).
Back to the question at the beginning of this article: Why does Python have the pass statement, what problems can it solve (benefits), and what problems will it cause (disadvantages) without it?
Python uses the pass statement to support purely no-operation code blocks (empty functions, empty classes, empty loop control blocks, etc.). With it, additional expressions can be Come up with a placeholder semantics.
The former is for machines and must be present, equivalent to the function of empty curly braces in other languages; the latter is for humans and is not necessary and can be expressed with comments. , but because Python designed this statement, this usage is sometimes quite convenient.
Related free learning recommendations: python video tutorial
The above is the detailed content of Do you know why Python has a pass statement?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.
