Python recognizes code blocks through indentation.
indentation
The most distinctive feature of Python is the use of indentation to indicate blocks of code. Let me take the if selection structure as an example. If is followed by a condition, if the condition is true, a code block belonging to if is executed.
First look at the expression of C language (note that this is C, not Python!)
if( i 0){
x =1;
y =2;}
If i is 0, we will perform the two assignment operations included in the brackets. What is contained in the brackets is the block operation, which belongs to if.
In Python, for the same purpose, this passage is like this
if i 0:
x =1
y =2
In Python, the parentheses around i 0 are removed, and the semicolon at the end of each sentence is removed, and the curly braces representing the block have also disappeared.
There is an extra: (colon) after if ..., and the indentation with four spaces before x = 1 and y = 2. Through indentation, Python recognizes that these two sentences belong to if. The reason why Python is designed this way is purely for the beauty of the program.
Example extension:
Python code indentation
Python functions have no obvious begin and end, and no curly braces to indicate the beginning and end of the function. The only separator is a colon (: ), and then the code itself is indented.
For example: indent buil dCon necti onStr ing function
def buildConnectionString(params):"""Build a connection string from a dictionary of parameters.
Returns string."""
return";".join(["%s=%s"%(k, v)for k, v in params.items()])
Code blocks are defined by their indentation. By "code block" I mean: functions, if statements, for loops, while loops, and so on. The start indentation indicates the beginning of the block, and the cancellation of the indentation indicates the end of the block. There are no obvious brackets, braces or keywords. This means that whitespace is important and consistent. In this example, the function code (including the doc string) is indented 4 spaces. It does not have to be 4, as long as they are consistent. The first line that is not indented is considered to be outside the function body.
Recommended Posts