Home > Article > Backend Development > A brief introduction to Python line structure and indentation
This article brings you a brief introduction to Python line structure and indentation. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Every statement in a Python program ends with a newline character. Use the line continuation character () to divide a long statement into several lines, as shown below:
x=math.cos(3*(x-n))+\ math.sin(3*(y-n))
In addition, the line continuation character does not need to be used for the definition of triple-quoted strings, lists, tuples, and dictionaries.
Generally speaking, any program part contained in parentheses (), square brackets [ ], curly brackets { } or triple quotes can be placed on multiple lines without using line continuation characters.
Indentation is used to indicate different blocks of code, such as functions, conditional statements, loops, and the main body of a class.
The indentation amount of the first statement in the code block can be arbitrary, but the indentation of the entire code block must be consistent, for example:
if a: statement1 statement2 #缩进一致,正确 else: statement3 statement4 #缩进不一致,错误
If a function, conditional statement, loop or The subject of a class is relatively short and contains only one statement. It can be placed on the first line, for example:
if a: statement1 else: statement2
To identify an empty topic or code block, you can use the pass statement, for example:
if a: pass else: statement
Although tabs can be used instead of indentation, it is better to use spaces to avoid unknown errors.
Like Java, Python can also add; as a separator after the statement, but this is not necessary in Python, unless you plan to write multiple statements in one line, separate them with;.
# indicates that this line is followed by a comment.
Unless in interactive mode (in interactive mode, blank marks the end of input), the parser will ignore all blank lines, so for the sake of beautiful code, it should be blank.
Related recommendations:
Introduction to Python basic indentation and selection
Python for loop statement structure and usage examples (picture)
The above is the detailed content of A brief introduction to Python line structure and indentation. For more information, please follow other related articles on the PHP Chinese website!