Python has strict requirements for indentation. The following article will give you an in-depth understanding of the code indentation rules in python. I hope it will be helpful to you!
Python uses indentation to distinguish different code blocks, so it has strict requirements for indentation.
1. The indentation does not comply with the rules. The parser will report an indentation error and the program cannot run.
#2. Depending on the indentation, the effect of program execution may also be different.
For example, in the code in the picture, the code on the left will print line 2, while the code on the right will not print lines 1 and 2
Indentation is for logical lines, so you must first distinguish between physical lines and logical lines in the code.
Physical lines: The code displayed in the code editor, each line is a physical line.
Logical line: The Python interpreter interprets the code, and a statement is a logical line.
In python code
1. You can use ";"# The ## sign combines multiple logical lines into one physical line.
##**There is a premise here, more logical lines should belong to the same code level.
# Branch else code blocks like this cannot be connected directly using ";". 2. You can use
"\" to wrap a logical line and write it as multiple physical lines.
#3. Variable assignment statements such as dictionaries and lists can be directly wrapped and written as multiple physical lines.
Indentation rules1. The "first line" of a logical line requires a top space , that is, no indentation (that is, the first logical line of a source code)
2. The same logical layer (the same code block) maintains the same indentation amount
3,
":"
such as: while loop, if branch, function declaration, class Definition, etc.Increase the indentation to enter the next code layer
Python can use spaces or tab characters (tab characters) to mark indentation. There is no limit to the amount of indentation (number of characters). The
space and tab
characters are usually displayed in blank form. It is difficult to distinguish them when used together, which affects code reading and increases maintenance and debugging. difficulty. Therefore, the Python PEP8 coding specification guides the use of 4 spaces as indentation.
In actual development, the code size is large and the indentation depth is affected. 2 spaces will be selected as the indentation. , easier to read.
【Related recommendations: Python3 video tutorial】
The above is the detailed content of Deep understanding of code indentation rules in python. For more information, please follow other related articles on the PHP Chinese website!