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!

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool