Why doesn't Python use a semicolon as a terminator?
Posted May 27, 2020 • 2 min read
Generally speaking, semicolons ";" are used in programming languages to achieve two purposes:
- As a statement delimiter:Use a semicolon to separate statements, so that multiple statements can be written in one line of code(multiple sentences in one line)
- As a statement terminator:use a semicolon to terminate the statement, so that multiple lines of code can be recognized as one statement(one line with multiple lines)
Just looking at "separator" and "terminator", they are both necessary, but should they be represented by semicolons? There is no agreed standard on this issue.
In Python, a semicolon is used as a statement delimiter, but instead of a semicolon as a terminator, a newline is used as a terminator.
If you add a semicolon at the end of a complete statement and then wrap it, the IDE will generally prompt "Trailing semicolon in the statement", indicating that this "trailing semicolon" is redundant.
According to my superficial understanding, the trailing semicolon will actually be regarded as a separator, except that it is followed by an "empty statement" and then a newline(that is, a terminator). Separating empty sentences is not necessary, so trailing semicolons become redundant.
Python does not use a semicolon as a terminator, probably for the following reasons:
- It treats indentation and line breaks as an effective part of the grammar, which can express complete semantics without causing ambiguity at compile time. This is the main reason, which is the fundamental difference from the "Semicolon Party"
- Do not use semicolons and curly braces, but use indentation and colons. This is the same line of thinking, and it has formed a higher readability, conciseness and standardization in general. This reflects the relationship between local grammar and overall rules, 1 + 1> 2
- You can write less characters and avoid the trouble of hitting the "shift" key on some keyboards
- The semicolon is mainly for the machine, but Python pays more attention to humanization. Early hardware has limitations, and adding semicolons can increase the speed of parsing/compilation, but now the obstacles have been removed, and some semicolon party languages are just continuing the old tradition of B/C language
- For statements that require line breaks, Python uses a backslash() to connect. It can be understood that it escapes line breaks, which can solve the problem of multiple lines.
![Python cat background reply "0527" to receive]( https://i0.wp.com/segmentfault.com/img/remote/1460000022766240 "Python cat background reply" 0527 "to receive")
written at the end
This article belongs to the "Python Why" series of articles(produced by the Python cat). This series mainly focuses on Python's grammar, design, and development. It uses "Why" questions as an entry point to try to show the charm of Python. More details: Video address