python Sensitive to indentation , Most tutorials are about indentation rules , Often just a few words , For beginners who have no other language foundation , Very unfriendly , In this paper python Common indentation problems have been sorted out .
One 、Python Indent length and indent characters I often see some Python Indent wrong interpretation ,“tab Character and space as indents cannot be mixed ”、“ The indent must be 4 A space ”. In fact, there are no such restrictions , For example, the example in the figure can work normally .
Space and tab Symbols are usually displayed as white space . If you mix , Code is easily confused , Increase the difficulty of maintenance and commissioning 、 Reduced code readability . therefore Python PEP8 Coding standards , Guide the use of 4 Space as indent . And the actual development , The choice of code will be more complex 2 Space as indent , This makes it easier to read deeply nested code .
Two 、Python Code indentation rules 1. The concept of physical line and logical line Judge indentation , First, distinguish between physical lines and logical lines , Indents are for logical lines .
Physics : The code displayed in the code editor , Each line is a physical line .
Logical line :Python The interpreter interprets the code , A statement is a logical line .
python In the code 1、 Use ";" Number combines two or more logical lines into one physical line . 2、 Use "" No. connects two physical lines . 3、 Dictionaries 、 List and other variable assignment statements , It can be written directly into multiple physical lines .
2. Indent rules 1、 Logical line “ First line ” Need top grid , No indent ( That is, the first logical line of a source code )
2、 The same logical layer keeps the same indentation
3、":" Mark a new logical layer Adding indents indicates moving to the next code layer Reducing indentation means returning to the previous code layer
3、 ... and 、 Commonly used python IDE Indent related 1、 frequently-used IDE There is an automatic indentation mechanism , The input “:” After number , Press “ enter ” Automatically indents . for example pycharm Code editing for :
2、 Set what character to use to identify indents 、tab As an indent 、 One tab Instead of a few spaces 、 Line join indent , wait .