Why doesn't Python use a semicolon as a terminator?

Generally speaking, semicolons ";" are used in programming languages ​​for two purposes:

  1. As a statement separator: use a semicolon to separate statements, so that you can write multiple statements in one line of code (multiple statements on one line)
  2. As a statement terminator: use a semicolon to terminate a statement, so that multiple lines of code are recognized as one statement (multiple lines)

Just look at the "separator" and "terminator", they are all necessary, but are they all represented by a semicolon? There is no agreed standard for this issue.

Python uses a semicolon as a statement separator, but instead of a semicolon as a terminator, a newline is used as a terminator.

If a semicolon is added at the end of a complete statement, followed by a line break, the IDE will generally prompt "Trailing semicolon in the statement", indicating that the "trailing semicolon" is redundant.

From my superficial understanding, the trailing semicolon is actually used as a delimiter, except that it is followed by an "empty statement", followed by a newline (i.e. terminator). Separating empty statements is unnecessary, so the trailing semicolon becomes redundant.

Python does not use a semicolon as a terminator, probably for the following reasons:

  1. It treats indentation and line breaks as valid parts of the grammar, expressing complete semantics without causing compile-time ambiguity. This is the main reason, which is the fundamental difference from the "semicolon party"
  2. No semicolons and curly braces, but indentation and colons, this is the same line of thinking, resulting in higher readability, brevity, and standardization overall. This reflects the relationship between the local grammar and the overall rule, 1 + 1 > 2
  3. Can write fewer characters and avoid the hassle of hitting the "shift" key on some keyboards
  4. Semicolons are mostly for machines, but Python is more human-friendly. There were some limitations in early hardware. Adding semicolons can improve the speed of parsing/compiling, but now the obstacle has been removed, and some semicolon party languages ​​are just continuing the old tradition of B/C languages.
  5. For statements that require a newline, Python uses a backslash (\) to connect, which can be understood as escaping the newline, which can solve the problem of multiple lines.

Python cat background reply "0527" to receive

Related reading

1、A Brief History of the Semicolon in Programming

2、The End of the Semicolon Era

write at the end

This article belongs to the "Why Python" series of articles (produced by Python Cat), which mainly focuses on topics such as Python's syntax, design, and development, and tries to show the charming charm of Python by starting with "why" questions. More details: Video URL

{{o.name}}
{{m.name}}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324128079&siteId=291194637