2022/01/07  阅读:42  主题:红绯


A Quick Tour of Python Language Syntax

Python 语言语法简介

< How to Run Python Code | Contents | Basic Python Semantics: Variables and Objects >

< 如何运行 Python 代码 | 内容 | 基本 Python 语义: 变量和对象 >

Python was originally developed as a teaching language, but its ease of use and clean syntax have led it to be embraced by beginners and experts alike. The cleanliness of Python's syntax has led some to call it "executable pseudocode", and indeed my own experience has been that it is often much easier to read and understand a Python script than to read a similar script written in, say, C. Here we'll begin to discuss the main features of Python's syntax.

Python 最初是作为一种教学语言开发的,但它的易用性和简洁的语法使它受到初学者和专家的欢迎。Python 清晰的语法使得一些人称之为“可执行的伪代码”,事实上我自己的经验是,阅读和理解 Python 脚本通常比阅读用 c 语言编写的类似脚本要容易得多。在这里,我们将开始讨论 Python 语法的主要特性。

Syntax refers to the structure of the language (i.e., what constitutes a correctly-formed program). For the time being, we'll not focus on the semantics – the meaning of the words and symbols within the syntax – but will return to this at a later point.


Consider the following code example:


In [1]: 在[1]中:

# set the midpoint
midpoint = 5

# make two empty lists
lower = []; upper = []

# split the numbers into lower and upper
for i in range(10):
    if (i < midpoint):

print("lower:", lower)
print("upper:", upper)
lower: [0, 1, 2, 3, 4]
upper: [5, 6, 7, 8, 9]

This script is a bit silly, but it compactly illustrates several of the important aspects of Python syntax. Let's walk through it and discuss some of the syntactical features of Python

这个脚本有点傻,但它简洁地说明了 Python 语法的几个重要方面。让我们逐一介绍一下,并讨论 Python 的一些语法特性

Comments Are Marked by 注释标记为#

The script starts with a comment:


# set the midpoint

Comments in Python are indicated by a pound sign (#), and anything on the line following the pound sign is ignored by the interpreter. This means, for example, that you can have stand-alone comments like the one just shown, as well as inline comments that follow a statement. For example:

Python 中的注释用磅符号(#)表示,并且解释器会忽略行中磅符号后面的任何内容。这意味着,例如,您可以拥有像刚才显示的那样的独立注释,以及语句后面的内联注释。例如:

x += 2  # shorthand for x = x + 2

Python does not have any syntax for multi-line comments, such as the /* ... */ syntax used in C and C++, though multi-line strings are often used as a replacement for multi-line comments (more on this in String Manipulation and Regular Expressions).

Python 没有任何针对多行注释的语法,比如 c 和 c + + 中使用的/* ... */语法,尽管多行字符串通常用于替代多行注释(更多内容见 String Manipulation and Regular Expressions)。

End-of-Line Terminates a Statement 行尾终止语句

The next line in the script is


midpoint = 5

This is an assignment operation, where we've created a variable named midpoint and assigned it the value 5. Notice that the end of this statement is simply marked by the end of the line. This is in contrast to languages like C and C++, where every statement must end with a semicolon (;).

这是一个赋值操作,我们创建了一个名为 midpoint 的变量,并将其赋值为5。注意,这个语句的结尾只是简单地用行尾标记。这与 c 和 c + + 等语言不同,后者的每个语句都必须以分号(;)结束。

In Python, if you'd like a statement to continue to the next line, it is possible to use the "\" marker to indicate this:

在 Python 中,如果希望语句继续到下一行,可以使用“”标记来表示:

In [2]: 在[2] :

x = 1 + 2 + 3 + 4 +\
    5 + 6 + 7 + 8

It is also possible to continue expressions on the next line within parentheses, without using the "\" marker:


In [3]: 在[3]中:

x = (1 + 2 + 3 + 4 +
     5 + 6 + 7 + 8)

Most Python style guides recommend the second version of line continuation (within parentheses) to the first (use of the "\" marker).

大多数 Python 样式指南推荐第二个版本的行继续(在括号内)到第一个版本(使用“”标记)。

Semicolon Can Optionally Terminate a Statement 分号可以选择终止语句

Sometimes it can be useful to put multiple statements on a single line. The next portion of the script is


lower = []; upper = []

This shows the example of how the semicolon (;) familiar in C can be used optionally in Python to put two statements on a single line. Functionally, this is entirely equivalent to writing

这个示例演示了如何在 Python 中选择使用 c 中熟悉的分号(;)将两个语句放在一行上。从功能上讲,这完全等同于写作

lower = []
upper = []

Using a semicolon to put multiple statements on a single line is generally discouraged by most Python style guides, though occasionally it proves convenient.

大多数 Python 样式指南通常不鼓励使用分号将多个语句放在一行上,尽管有时候这样做很方便。

Indentation: Whitespace Matters! 缩进: 空格很重要

Next, we get to the main block of code:


for i in range(10):
    if i < midpoint:

This is a compound control-flow statement including a loop and a conditional – we'll look at these types of statements in a moment. For now, consider that this demonstrates what is perhaps the most controversial feature of Python's syntax: whitespace is meaningful!

这是一个复合的控制流语句,包括一个循环和一个条件语句——稍后我们将研究这些类型的语句。现在,考虑一下这个演示可能是 Python 语法中最有争议的特性: 空格是有意义的!

In programming languages, a block of code is a set of statements that should be treated as a unit. In C, for example, code blocks are denoted by curly braces:

在编程语言中,代码块是一组应当作为一个单元处理的语句。例如,在 c 语言中,代码块用大括号表示:

// C code
for(int i=0; i<100; i++)
      // curly braces indicate code block
      total += i;

In Python, code blocks are denoted by indentation:

在 Python 中,代码块用缩进表示:

for i in range(100):
    # indentation indicates code block
    total += i

In Python, indented code blocks are always preceded by a colon (:) on the previous line.

在 Python 中,缩进代码块的前一行总是带有冒号(:)。

The use of indentation helps to enforce the uniform, readable style that many find appealing in Python code. But it might be confusing to the uninitiated; for example, the following two snippets will produce different results:

缩进的使用有助于强化统一的、可读的样式,这种样式在 Python 代码中很受欢迎。但是这可能会让外行人感到困惑; 例如,下面的两个片段会产生不同的结果:

>>> if x < 4:         >>> if x < 4:
...     y = x * 2     ...     y = x * 2
...     print(x)      ... print(x)

In the snippet on the left, print(x) is in the indented block, and will be executed only if x is less than 4. In the snippet on the right print(x) is outside the block, and will be executed regardless of the value of x!

在左侧的代码片段中,print (x)位于缩进块中,只有当 x 小于4时才执行。在右边 print (x)上的代码片段位于块之外,并且不管 x 的值是多少都会被执行!

Python's use of meaningful whitespace often is surprising to programmers who are accustomed to other languages, but in practice it can lead to much more consistent and readable code than languages that do not enforce indentation of code blocks. If you find Python's use of whitespace disagreeable, I'd encourage you to give it a try: as I did, you may find that you come to appreciate it.

对于习惯于其他语言的程序员来说,Python 使用有意义的空格常常是令人惊讶的,但是在实践中,与不强制缩进代码块的语言相比,它可以导致更加一致和可读的代码。如果你不喜欢 Python 使用空格,我鼓励你尝试一下: 正如我所做的,你可能会发现你开始欣赏它。

Finally, you should be aware that the amount of whitespace used for indenting code blocks is up to the user, as long as it is consistent throughout the script. By convention, most style guides recommend to indent code blocks by four spaces, and that is the convention we will follow in this report. Note that many text editors like Emacs and Vim contain Python modes that do four-space indentation automatically.

最后,您应该知道缩进代码块所使用的空白数量取决于用户,只要整个脚本中的空白数量是一致的。按照惯例,大多数样式指南建议将代码块缩进四个空格,这也是我们将在本报告中遵循的惯例。请注意,许多文本编辑器(如 Emacs 和 Vim)都包含自动进行四空间缩进的 Python 模式。

Whitespace 空白Within 内部 Lines Does Not Matter 线条并不重要

While the mantra of meaningful whitespace holds true for whitespace before lines (which indicate a code block), white space within lines of Python code does not matter. For example, all three of these expressions are equivalent:

虽然行之前的空格符合有意义的空格符号(表示代码块) ,但 Python 代码行内的空格并不重要。例如,这三个表达式都是等价的:

In [4]: 在[4] :

x = 1 + 2
x             =        1    +                2

Abusing this flexibility can lead to issues with code readibility – in fact, abusing white space is often one of the primary means of intentionally obfuscating code (which some people do for sport). Using whitespace effectively can lead to much more readable code, especially in cases where operators follow each other – compare the following two expressions for exponentiating by a negative number:




x = 10 ** -2

I find the second version with spaces much more easily readable at a single glance. Most Python style guides recommend using a single space around binary operators, and no space around unary operators. We'll discuss Python's operators further in Basic Python Semantics: Operators.

我发现第二个版本的空格更容易阅读一眼。大多数 Python 样式指南建议在二进制操作符周围使用单一空格,而在一元操作符周围不要使用空格。我们将在基本 Python 语义: 操作符中进一步讨论 Python 的操作符。

Parentheses Are for Grouping or Calling 圆括号用于分组或调用

In the previous code snippet, we see two uses of parentheses. First, they can be used in the typical way to group statements or mathematical operations:


In [5]: 在[5] :

2 * (3 + 4)

Out[5]: 出局[5] :


They can also be used to indicate that a function is being called. In the next snippet, the print() function is used to display the contents of a variable (see the sidebar). The function call is indicated by a pair of opening and closing parentheses, with the arguments to the function contained within:

它们也可以用来表示正在调用某个函数。在下一个代码片段中,print ()函数用于显示变量的内容(参见边栏)。函数调用由一对开括号和结束括号表示,参数包含在:

In [6]: 在[6] :

print('first value:', 1)
first value: 1

In [7]: 在[7]中:

print('second value:', 2)
second value: 2

Some functions can be called with no arguments at all, in which case the opening and closing parentheses still must be used to indicate a function evaluation. An example of this is the sort method of lists:


In [8]: 在[8]中:

L = [4,2,3,1]
[1, 2, 3, 4]

The "()" after sort indicates that the function should be executed, and is required even if no arguments are necessary.

Sort 后面的“()”表示应该执行该函数,即使没有必要的参数也是必需的。

Aside: A Note on the 旁白: 关于print() Function 功能

Above we used the example of the print() function. The print() function is one piece that has changed between Python 2.x and Python 3.x. In Python 2, print behaved as a statement: that is, you could write

上面我们使用了 print ()函数的示例。Print ()函数是在 python2.x 和 python3.x 之间进行了更改的一部分。在 Python 2中,print 表现为一个语句: 也就是说,你可以编写

# Python 2 only!
>> print "first value:", 1
first value: 1

For various reasons, the language maintainers decided that in Python 3 print() should become a function, so we now write

出于各种原因,语言维护人员决定在 python3print ()中使用一个函数,因此我们现在编写

# Python 3 only!
>>> print("first value:", 1)
first value: 1

This is one of the many backward-incompatible constructs between Python 2 and 3. As of the writing of this book, it is common to find examples written in both versions of Python, and the presence of the print statement rather than the print() function is often one of the first signs that you're looking at Python 2 code.

这是 python2和 python3之间许多向后不兼容的结构之一。在写这本书的时候,发现用两个版本的 Python 编写的例子是很常见的,而 print 语句而不是 print ()函数的出现通常是 Python 2代码的第一个标志之一。

Finishing Up and Learning More 完成和学习更多

This has been a very brief exploration of the essential features of Python syntax; its purpose is to give you a good frame of reference for when you're reading the code in later sections. Several times we've mentioned Python "style guides", which can help teams to write code in a consistent style. The most widely used style guide in Python is known as PEP8, and can be found at https://www.python.org/dev/peps/pep-0008/. As you begin to write more Python code, it would be useful to read through this! The style suggestions contain the wisdom of many Python gurus, and most suggestions go beyond simple pedantry: they are experience-based recommendations that can help avoid subtle mistakes and bugs in your code.

本文对 Python 语法的基本特性进行了非常简短的探讨; 其目的是为您在后面的章节中阅读代码时提供一个很好的参考框架。我们多次提到 Python“样式指南”,它可以帮助团队以一致的样式编写代码。在 Python 中使用最广泛的样式指南被称为 PEP8,可以在 https://www.Python.org/dev/peps/pep-0008/中找到。当您开始编写更多的 Python 代码时,通读这篇文章将会非常有用!这些样式建议包含了许多 Python 大师的智慧,而且大多数建议都超越了简单的迂腐: 它们是基于经验的建议,可以帮助避免代码中的细微错误和 bug。


2022/01/07  阅读:42  主题:红绯