构建Python程序

You have now covered Python variables, operators, and data types in depth, and you’ve seen quite a bit of example code. Up to now, the code has consisted of short individual statements, simply assigning objects to variables or displaying values.

现在,您已经深入介绍了Python变量,运算符和数据类型,并且已经看到了很多示例代码。 到目前为止,该代码由简短的单个语句组成,只需将对象分配给变量或显示值即可。

But you want to do more than just define data and display it! Let’s start arranging code into more complex groupings.

但是,您要做的不仅仅是定义数据并显示它! 让我们开始将代码安排到更复杂的分组中。

Here’s what you’ll learn in this tutorial: You’ll dig deeper into Python lexical structure. You’ll learn about the syntactic elements that comprise statements, the basic units that make up a Python program. This will prepare you for the next few tutorials covering control structures, constructs that direct program flow among different groups of code.

这是您在本教程中将学到的内容:您将更深入地研究Python 词法结构 。 您将学习组成语句的语法元素,这些语句是构成Python程序的基本单元。 这将为您准备接下来的几篇涵盖控制结构的教程,这些结构指导程序在不同代码组之间的流程。

Python语句 (Python Statements)

Statements are the basic units of instruction that the Python interpreter parses and processes. In general, the interpreter executes statements sequentially, one after the next as it encounters them. (You will see in the next tutorial on conditional statements that it is possible to alter this behavior.)

语句是Python解释器解析和处理的基本指令单元。 通常,解释器顺序执行语句,遇到语句时依次执行。 (您将在下一个关于条件语句的教程中看到可以更改此行为。)

In a REPL session, statements are executed as they are typed in, until the interpreter is terminated. When you execute a script file, the interpreter reads statements from the file and executes them until end-of-file is encountered.

在REPL会话中,语句在键入时执行,直到解释器终止。 当您执行脚本文件时,解释器将从文件中读取语句并执行它们,直到遇到文件结尾。

Python programs are typically organized with one statement per line. In other words, each statement occupies a single line, with the end of the statement delimited by the newline character that marks the end of the line. The majority of the examples so far in this tutorial series have followed this pattern:

Python程序通常每行用一条语句来组织。 换句话说,每个语句只占一行,语句的结尾由标记该行结尾的换行符分隔。 到目前为止,本教程系列中的大多数示例都遵循以下模式:

 >>> >>>  printprint (( 'Hello, World!''Hello, World!' )
)
Hello, World!

Hello, World!

>>> >>>  x x = = [[ 11 , , 22 , , 33 ]
]
>>> >>>  printprint (( xx [[ 11 :: 22 ])
])
[2]
[2]

Note: In many of the REPL examples you have seen, a statement has often simply consisted of an expression typed directly at the >>> prompt, for which the interpreter dutifully displays the value:

注意:在您看到的许多REPL示例中,一条语句通常只是由直接在>>>提示符下键入的表达式组成,对于该表达式 ,解释器会忠实地显示值:

Remember that this only works interactively, not from a script file. In a script file, a literal or expression that appears as a solitary statement like the above will not cause output to the console. In fact, it won’t do anything useful at all. Python will simply waste CPU time calculating the value of the expression, and then throw it away.

请记住,这只能以交互方式起作用,而不是从脚本文件中起作用。 在脚本文件中,像上述那样作为单独语句出现的文字或表达式不会导致输出到控制台。 实际上,它根本没有任何用处。 Python只会浪费CPU时间来计算表达式的值,然后将其丢弃。

线延续 (Line Continuation)

Suppose a single statement in your Python code is especially long. For example, you may have an assignment statement with many terms:

假设您的Python代码中的一条语句特别长。 例如,您可能有一个包含许多术语的赋值语句:

 >>> >>>  person1_age person1_age = = 42
42
>>> >>>  person2_age person2_age = = 16
16
>>> >>>  person3_age person3_age = = 71

71

>>> >>>  someone_is_of_working_age someone_is_of_working_age = = (( person1_age person1_age >= >= 18 18 and and person1_age person1_age <= <= 6565 ) ) or or (( person2_age person2_age >= >= 18 18 and and person2_age person2_age <= <= 6565 ) ) or or (( person3_age person3_age >= >= 18 18 and and person3_age person3_age <= <= 6565 )
)
>>> >>>  someone_is_of_working_age
someone_is_of_working_age
True
True

Or perhaps you are defining a lengthy nested list:

或者,也许您正在定义一个冗长的嵌套列表:

You’ll notice that these statements are too long to fit in your browser window, and the browser is forced to render the code blocks with horizontal scroll bars. You may find that irritating. (You have our apologies—these examples are presented that way to make the point. It won’t happen again.)

您会注意到这些语句太长而无法容纳在浏览器窗口中,并且浏览器被迫使用水平滚动条呈现代码块。 您可能会发现这很烦人。 (很抱歉,这些示例是为了说明这一点而提出的。以后不会再发生。)

It is equally frustrating when lengthy statements like these are contained in a script file. Most editors can be configured to wrap text, so that the ends of long lines are at least visible and don’t disappear out the right edge of the editor window. But the wrapping doesn’t necessarily occur in logical locations that enhance readability:

当类似冗长的语句包含在脚本文件中时,这同样令人沮丧。 可以将大多数编辑器配置为自动换行,以使长行的末端至少可见,并且不会在编辑器窗口的右边缘消失。 但是包装不一定发生在可增强可读性的逻辑位置:

line-wrap

Excessively long lines of code are generally considered poor practice. In fact, there is an official Style Guide for Python Code put forth by the Python Software Foundation, and one of its stipulations is that the maximum line length in Python code should be 79 characters.

太长的代码行通常被认为是不好的做法。 实际上,Python软件基金会已经发布了一份正式的Python代码样式指南 ,其中一项规定是Python代码的最大行长应为79个字符。

Note: The Style Guide for Python Code is also referred to as PEP 8. PEP stands for Python Enhancement Proposal. PEPs are documents that contain details about features, standards, design issues, general guidelines, and information relating to Python. For more information, see the Python Software Foundation Index of PEPs.

注意: Python代码样式指南也称为PEP 8 。 PEP代表Python增强提案。 PEP是包含有关功能,标准,设计问题,一般准则以及与Python有关的信息的详细信息的文档。 有关更多信息,请参阅PEP的Python软件基础索引

As code becomes more complex, statements will on occasion unavoidably grow long. To maintain readability, you should break them up into parts across several lines. But you can’t just split a statement whenever and wherever you like. Unless told otherwise, the interpreter assumes that a newline character terminates a statement. If the statement isn’t syntactically correct at that point, an exception is raised:

随着代码变得更加复杂,语句有时会不可避免地变长。 为了保持可读性,您应该将它们分成几行。 但是您不能随便在任何地方拆分一条语句。 除非另有说明,否则解释器会假定换行符会终止语句。 如果此时的语句在语法上不正确,则会引发异常:

 >>> >>>  someone_is_of_working_age someone_is_of_working_age = = person1_age person1_age >= >= 18 18 and and person1_age person1_age <= <= 65 65 or
or
SyntaxError: invalid syntax
SyntaxError: invalid syntax

In Python code, a statement can be continued from one line to the next in two different ways: implicit and explicit line continuation.

在Python代码中,语句可以以两种不同的方式从一行继续到下一行:隐式和显式的行连续。

隐式连续线 (Implicit Line Continuation)

This is the more straightforward technique for line continuation, and the one that is preferred according to PEP 8.

这是用于行连续的更直接的技术,根据PEP 8首选。

Any statement containing opening parentheses ('('), brackets ('['), or curly braces ('{') is presumed to be incomplete until all matching parentheses, brackets, and braces have been encountered. Until then, the statement can be implicitly continued across lines without raising an error.

在遇到所有匹配的括号,方括号和花括号之前,任何包含开括号( '(' ),方括号( '[' )或花括号( '{' ))的语句都被认为是不完整的。跨行隐式继续而不会引发错误。

For example, the nested list definition from above can be made much more readable using implicit line continuation because of the open brackets:

例如,由于使用了方括号,因此可以使用隐式行连续使上面的嵌套列表定义更具可读性:

A long expression can also be continued across multiple lines by wrapping it in grouping parentheses. PEP 8 explicitly advocates using parentheses in this manner when appropriate:

通过将其括在分组括号中,长表达式也可以跨多行继续。 PEP 8明确主张在适当时以这种方式使用括号:

 >>> >>>  someone_is_of_working_age someone_is_of_working_age = = (
(
...     ...     (( person1_age person1_age >= >= 18 18 and and person1_age person1_age <= <= 6565 )
)
...     ...     or or (( person2_age person2_age >= >= 18 18 and and person2_age person2_age <= <= 6565 )
)
...     ...     or or (( person3_age person3_age >= >= 18 18 and and person3_age person3_age <= <= 6565 )
)
... ...  )

)

>>> >>>  someone_is_of_working_age
someone_is_of_working_age
True
True

If you need to continue a statement across multiple lines, it is usually possible to use implicit line continuation to do so. This is because parentheses, brackets, and curly braces appear so frequently in Python syntax:

如果需要跨多行继续执行一条语句,通常可以使用隐式行继续来执行。 这是因为括号,方括号和花括号在Python语法中出现得如此频繁:

括弧 (Parentheses)
  • Expression grouping

  • Function call

    >>> print(
    ...     'foo',
    ...     'bar',
    ...     'baz'
    ... )
    foo bar baz
    
    
  • Method call

  • Tuple definition

    >>> t = (
    ...     'a', 'b',
    ...     'c', 'd'
    ... )
    
    
  • 表达式分组

  • 函数调用

     >>>  print (
    ...     'foo' ,
    ...     'bar' ,
    ...     'baz'
    ...  )
    foo bar baz
    
  • 方法调用

  • 元组定义

     >>>  t = (
    ...     'a' , 'b' ,
    ...     'c' , 'd'
    ...  )
    
大括号 (Curly Braces)
  • Dictionary definition

  • Set definition

    >>> x1 = {
    ...     'foo',
    ...     'bar',
    ...     'baz'
    ... }
    
    
  • 字典定义

  • 集合定义

     >>>  x1 = {
    ...     'foo' ,
    ...     'bar' ,
    ...     'baz'
    ...  }
    
方括号 (Square Brackets)
  • List definition

  • Indexing

    >>> a[
    ...  1
    ...  ]
    'bar'
    
    
  • Slicing

  • Dictionary key reference

    >>> d[
    ...  'b'
    ...  ]
    2
    
    
  • 清单定义

  • 索引编制

     >>>  a [
    ...  1
    ...  ]
    'bar'
    
  • 切片

  • 字典键参考

     >>>  d [
    ...  'b'
    ...  ]
    2
    

Note: Just because something is syntactically allowed, it doesn’t mean you should do it. Some of the examples above would not typically be recommended. Splitting indexing, slicing, or dictionary key reference across lines, in particular, would be unusual. But you can consider it if you can make a good argument that it enhances readability.

注意:仅仅因为语法上允许某事,并不意味着您应该这样做。 通常不建议使用上述某些示例。 特别是,跨行拆分索引,切片或字典键引用将是异常的。 但是,如果可以提出一个很好的论据来增强可读性,则可以考虑使用它。

Remember that if there are multiple parentheses, brackets, or curly braces, then implicit line continuation is in effect until they are all closed:

请记住,如果有多个括号,方括号或花括号,则隐式的行连续有效,直到它们都被关闭:

Note how line continuation and judicious use of indentation can be used to clarify the nested structure of the list.

请注意如何使用行连续和缩进的明智使用来阐明列表的嵌套结构。

显式行继续 (Explicit Line Continuation)

In cases where implicit line continuation is not readily available or practicable, there is another option. This is referred to as explicit line continuation or explicit line joining.

如果隐式的行连续性不易获得或不可行,则还有另一种选择。 这称为显式行连续或显式行连接。

Ordinarily, a newline character (which you get when you press Enter on your keyboard) indicates the end of a line. If the statement is not complete by that point, Python will raise a SyntaxError exception:

通常,换行符(当您按键盘上的Enter键时会得到)表示行的结尾。 如果到那时该语句还没有完成,Python将引发SyntaxError异常:

 >>> >>>  s s =
  File =
  File "<stdin>", line "<stdin>" , line 1
    1
    s s =
      =
      ^
^
SyntaxError: SyntaxError : invalid syntax

invalid syntax

>>> >>>  x x = = 1 1 + + 2 2 +
  File +
  File "<stdin>", line "<stdin>" , line 1
    1
    x x = = 1 1 + + 2 2 +
              +
              ^
^
SyntaxError: SyntaxError : invalid syntax
invalid syntax

To indicate explicit line continuation, you can specify a backslash () character as the final character on the line. In that case, Python ignores the following newline, and the statement is effectively continued on next line:

要指示明确的行继续,您可以指定反斜杠( )字符作为该行的最后一个字符。 在这种情况下,Python会忽略以下换行符,并在下一行有效地继续执行该语句:

Note that the backslash character must be the last character on the line. Not even whitespace is allowed after it:

请注意,反斜杠字符必须是该行的最后一个字符。 其后甚至不允许使用空格:

 >>> >>>  # You can't see it, but there is a space character following the  here:
# You can't see it, but there is a space character following the  here:
>>> >>>  s s = 
  File = 
  File "<stdin>", line "<stdin>" , line 1
    1
    s s = 
         = 
         ^
^
SyntaxError: SyntaxError : unexpected character after line continuation character
unexpected character after line continuation character

Again, PEP 8 recommends using explicit line continuation only when implicit line continuation is not feasible.

同样,PEP 8建议仅在隐式行连续不可行时才使用显式行连续。

每行多条语句 (Multiple Statements Per Line)

Multiple statements may occur on one line, if they are separated by a semicolon (;) character:

如果用分号( ; )字符分隔,则可能在一行上出现多个语句:

Stylistically, this is generally frowned upon, and PEP 8 expressly discourages it. There might be situations where it improves readability, but it usually doesn’t. In fact, it often isn’t necessary. The following statements are functionally equivalent to the example above, but would be considered more typical Python code:

从风格上讲,这通常是不被接受的, PEP 8显然不鼓励这样做 。 在某些情况下,它可以提高可读性,但通常不会。 实际上,这通常不是必需的。 以下语句在功能上与上面的示例等效,但是将被视为更典型的Python代码:

 >>> >>>  xx , , yy , , z z = = 11 , , 22 , , 3
3
>>> >>>  printprint (( xx , , yy , , zz , , sepsep == '' nn '' )
)
1
1
2
2
3
3

The term Pythonic refers to code that adheres to generally accepted common guidelines for readability and “best” use of idiomatic Python. When someone says code is not Pythonic, they are implying that it does not express the programmer’s intent as well as might otherwise be done in Python. Thus, the code is probably not as readable as it could be to someone who is fluent in Python.

术语Pythonic是指遵守关于可读性和“最佳”使用惯用Python的通用准则。 当有人说代码不是Python语言时,就意味着它不能表达程序员的意图,否则就不能用Python完成。 因此,对于精通Python的人来说,代码可能不那么可读。

If you find your code has multiple statements on a line, there is probably a more Pythonic way to write it. But again, if you think it’s appropriate or enhances readability, you should feel free to do it.

如果发现您的代码在一行上有多个语句,则可能存在一种更Python化的编写方式。 但是同样,如果您认为合适或可以提高可读性,则可以随意这样做。

注释 (Comments)

In Python, the hash character (#) signifies a comment. The interpreter will ignore everything from the hash character through the end of that line:

在Python中,井号( # )表示注释。 解释器将忽略从哈希字符到该行结尾的所有内容:

If the first non-whitespace character on the line is a hash, the entire line is effectively ignored:

如果该行的第一个非空白字符是哈希,则将有效地忽略整行:

 >>> >>>  # I am a comment.
# I am a comment.
>>>     >>>     # I am too.
# I am too.

Naturally, a hash character inside a string literal is protected, and does not indicate a comment:

自然地,字符串文字内的哈希字符受保护,并且不表示注释:

A comment is just ignored, so what purpose does it serve? Comments give you a way to attach explanatory detail to your code:

评论只是被忽略,所以它有什么作用? 注释使您可以将解释性详细信息附加到代码中:

 >>> >>>  # Calculate and display the area of a circle.

# Calculate and display the area of a circle.

>>> >>>  pi pi = = 3.1415926536
3.1415926536
>>> >>>  r r = = 12.35

12.35

>>> >>>  area area = = pi pi * * (( r r ** ** 22 )

)

>>> >>>  printprint (( 'The area of a circle with radius''The area of a circle with radius' , , rr , , 'is''is' , , areaarea )
)
The area of a circle with radius 12.35 is 479.163565508706
The area of a circle with radius 12.35 is 479.163565508706

Up to now, your Python coding has consisted mostly of short, isolated REPL sessions. In that setting, the need for comments is pretty minimal. Eventually, you will develop larger applications contained across multiple script files, and comments will become increasingly important.

到目前为止,您的Python编码主要由简短的独立REPL会话组成。 在这种情况下,对注释的需求很小。 最终,您将开发包含在多个脚本文件中的更大的应用程序,并且注释将变得越来越重要。

Good commenting makes the intent of your code clear at a glance when someone else reads it, or even when you yourself read it. Ideally, you should strive to write code that is as clear, concise, and self-explanatory as possible. But there will be times that you will make design or implementation decisions that are not readily obvious from the code itself. That is where commenting comes in. Good code explains how; good comments explain why.

良好的注释可以使您的代码意图在其他人阅读甚至您自己阅读时一目了然。 理想情况下,您应该努力编写尽可能清晰,简洁和易于解释的代码。 但是有时您可能会做出从代码本身不容易理解的设计或实现决策。 这就是注释的来源。好的代码解释了如何做。 好的评论解释了原因。

Comments can be included within implicit line continuation:

注释可以包含在隐式行继续中:

But recall that explicit line continuation requires the backslash character to be the last character on the line. Thus, a comment can’t follow afterward:

但是请记住,显式的行连续要求反斜杠字符是行上的最后一个字符。 因此,此后不能发表评论:

 >>> >>>  x x = = 1 1 + + 2 2 +    +    # I wish to be comment, but I'm not.
# I wish to be comment, but I'm not.
SyntaxError: unexpected character after line continuation character
SyntaxError: unexpected character after line continuation character

What if you want to add a comment that is several lines long? Many programming languages provide a syntax for multiline comments (also called block comments). For example, in C and Java, comments are delimited by the tokens /* and */. The text contained within those delimiters can span multiple lines:

如果要添加多行注释,该怎么办? 许多编程语言提供了多行注释(也称为块注释)的语法。 例如,在C和Java中,注释由标记/**/分隔。 这些定界符中包含的文本可以跨越多行:

Python doesn’t explicitly provide anything analogous to this for creating multiline block comments. To create a block comment, you would usually just begin each line with a hash character:

Python没有为创建多行块注释提供任何与此类似的功能。 要创建一个块注释,通常只需要在每行以一个哈希字符开始:

 >>> >>>  # Initialize value for radius of circle.
# Initialize value for radius of circle.
>>> >>>  #
#
>>> >>>  # Then calculate the area of the circle
# Then calculate the area of the circle
>>> >>>  # and display the result to the console.

# and display the result to the console.

>>> >>>  pi pi = = 3.1415926536
3.1415926536
>>> >>>  r r = = 12.35

12.35

>>> >>>  area area = = pi pi * * (( r r ** ** 22 )

)

>>> >>>  printprint (( 'The area of a circle with radius''The area of a circle with radius' , , rr , , 'is''is' , , areaarea )
)
The area of a circle with radius 12.35 is 479.163565508706
The area of a circle with radius 12.35 is 479.163565508706

However, for code in a script file, there is technically an alternative.

但是,对于脚本文件中的代码,从技术上讲还有一种选择。

You saw above that when the interpreter parses code in a script file, it ignores a string literal (or any literal, for that matter) if it appears as statement by itself. More precisely, a literal isn’t ignored entirely: the interpreter sees it and parses it, but doesn’t do anything with it. Thus, a string literal on a line by itself can serve as a comment. Since a triple-quoted string can span multiple lines, it can effectively function as a multiline comment.

您在上面看到了,当解释器解析脚本文件中的代码时,如果它本身显示为语句,则它将忽略字符串文字(或任何文字)。 更准确地说,文字不会被完全忽略:解释器会看到并解析它,但不会对其进行任何处理。 因此,一行上的字符串文字本身可以用作注释。 由于三引号字符串可以跨越多行,因此可以有效地用作多行注释。

Consider this script file foo.py:

考虑此脚本文件foo.py

When this script is run, the output appears as follows:

运行此脚本时,输出如下所示:

 C:UsersjohnDocumentsPythondoc>python foo.py
C:UsersjohnDocumentsPythondoc> python foo.py
The area of a circle with radius 12.35 is 479.163565508706
The area of a circle with radius 12.35 is 479.163565508706

The triple-quoted string is not displayed and doesn’t change the way the script executes in any way. It effectively constitutes a multiline block comment.

三引号的字符串不会显示,并且不会以任何方式更改脚本的执行方式。 它实际上构成了多行块注释。

Although this works (and was once put forth as a Python programming tip by Guido himself), PEP 8 actually recommends against it. The reason for this appears to be because of a special Python construct called the docstring. A docstring is a special comment at the beginning of a user-defined function that documents the function’s behavior. Docstrings are typically specified as triple-quoted string comments, so PEP 8 recommends that other block comments in Python code be designated the usual way, with a hash character at the start of each line.

尽管这行得通(并且曾经由Guido自己作为Python编程技巧提出过),但PEP 8实际上还是建议不要这样做。 出现这种情况的原因似乎是由于一种称为docstring的特殊Python构造。 文档字符串是在用户定义函数的开头的特殊注释,用于记录函数的行为。 文档字符串通常指定为用三引号引起来的字符串注释,因此PEP 8建议以通常的方式指定Python代码中的其他块注释 ,并在每行的开头添加一个哈希字符。

However, as you are developing code, if you want a quick and dirty way to comment out as section of code temporarily for experimentation, you may find it convenient to wrap the code in triple quotes.

但是,在开发代码时,如果您想要一种快速而又肮脏的方法暂时将其注释为代码部分以进行实验,则可以发现将代码用三引号引起来很方便。

Further Reading: You will learn more about docstrings in the upcoming tutorial on functions in Python.

进一步阅读:您将在即将到来的Python函数教程中学习有关文档字符串的更多信息。

For more information on commenting and documenting Python code, including docstrings, see Documenting Python Code: A Complete Guide.

有关注释和文档化Python代码(包括文档字符串)的更多信息,请参见文档化Python代码:完整指南

空格 (Whitespace)

When parsing code, the Python interpreter breaks the input up into tokens. Informally, tokens are just the language elements that you have seen so far: identifiers, keywords, literals, and operators.

解析代码时,Python解释器将输入分解为令牌。 非正式地,令牌只是您到目前为止所见的语言元素:标识符,关键字,文字和运算符。

Typically, what separates tokens from one another is whitespace: blank characters that provide empty space to improve readability. The most common whitespace characters are the following:

通常,将标记彼此分隔的是空格:空白字符可提供空白空间以提高可读性。 最常见的空格字符如下:

Character 字符 ASCII Code ASCII码 Literal Expression 文字表达
space 空间 32 (320x20)0x20' '' '
tab 标签 9 (90x9)0x9't''t'
newline 新队 10 (100xa)0xa'n''n'

There are other somewhat outdated ASCII whitespace characters such as line feed and form feed, as well as some very esoteric Unicode characters that provide whitespace. But for present purposes, whitespace usually means a space, tab, or newline.

还有其他一些过时的ASCII空格字符,例如换行符和换页符,以及提供空格的一些非常深奥的Unicode字符。 但是出于目前的目的,空格通常表示空格,制表符或换行符。

Whitespace is mostly ignored, and mostly not required, by the Python interpreter. When it is clear where one token ends and the next one starts, whitespace can be omitted. This is usually the case when special non-alphanumeric characters are involved:

Python解释器通常会忽略空格,并且大多数情况下不需要空格。 当清楚地知道一个令牌的结束位置和下一个令牌的起始位置时,可以省略空格。 当涉及特殊的非字母数字字符时,通常是这种情况:

Every one of the statements above has no whitespace at all, and the interpreter handles them all fine. That’s not to say that you should write them that way though. Judicious use of whitespace almost always enhances readability, and your code should typically include some. Compare the following code fragments:

上面的每个语句根本没有空格,并且解释器会很好地处理它们。 这并不是说您应该这样写。 明智地使用空格几乎总是可以提高可读性,并且您的代码通常应包含一些空格。 比较以下代码片段:

 >>> >>>  value1value1 == 100
100
>>> >>>  value2value2 == 200
200
>>> >>>  vv == (( value1value1 >=>= 00 )) andand (( value1value1 << value2value2 )
)

Most people would likely find that the added whitespace in the second example makes it easier to read. On the other hand, you could probably find a few who would prefer the first example. To some extent, it is a matter of personal preference. But there are standards for whitespace in expressions and statements put forth in PEP 8, and you should strongly consider adhering to them as much as possible.

大多数人可能会发现,第二个示例中添加的空格使它更易于阅读。 另一方面,您可能会找到一些更喜欢第一个示例的人。 在某种程度上,这是个人喜好问题。 但是,PEP 8 中的表达式和语句中空白的标准,因此您应该强烈考虑尽可能地遵守这些标准。

Note: You can juxtapose string literals, with or without whitespace:

注意:您可以将字符串文字并置,带或不带空格:

 >>> >>>  s s = = "foo""foo" 'bar''''baz'''
'bar''''baz'''
>>> >>>  s
s
'foobarbaz'

'foobarbaz'

>>> >>>  s s = = 'foo' 'foo' "bar" "bar" '''baz'''
'''baz'''
>>> >>>  s
s
'foobarbaz'
'foobarbaz'

The effect is concatenation, exactly as though you had used the + operator.

效果是串联,就像使用+运算符一样。

In Python, whitespace is generally only required when it is necessary to distinguish one token from the next. This is most common when one or both tokens are an identifier or keyword.

在Python中,通常仅在有必要将一个令牌与另一个令牌区分开时才需要空格。 当一个或两个令牌是标识符或关键字时,这是最常见的。

For example, in the following case, whitespace is needed to separate the identifier s from the keyword in:

例如,在以下情况下,需要使用空格将标识符s与关键字in分开:

Here is an example where whitespace is required to distinguish between the identifier y and the numeric constant 20:

这是一个示例,其中需要空格来区分标识符y和数字常量20

 >>> >>>  y y is is 20
20
False

False

>>> >>>  y y is20
is20
SyntaxError: invalid syntax
SyntaxError: invalid syntax

In this example, whitespace is needed between two keywords:

在此示例中,两个关键字之间需要空格:

Running identifiers or keywords together fools the interpreter into thinking you are referring to a different token than you intended: sin, is20, and notin, in the examples above.

一起运行标识符或关键字会使解释器is20以为您在指的是与预期不同的令牌:在上面的示例中, sinis20notin

All this tends to be rather academic because it isn’t something you’ll likely need to think about much. Instances where whitespace is necessary tend to be intuitive, and you’ll probably just do it by second nature.

所有这些趋向于是相当学术性的,因为您可能不需要考虑太多。 需要空格的实例通常很直观,您可能只是自然而然地做到了。

You should use whitespace where it isn’t strictly necessary as well to enhance readability. Ideally, you should follow the guidelines in PEP 8.

您也应该在并非绝对必要的地方使用空格,以提高可读性。 理想情况下,您应该遵循PEP 8中的准则。

Deep Dive: Fortran and Whitespace

深入探讨:Fortran和空白

The earliest versions of Fortran, one of the first programming languages created, were designed so that all whitespace was completely ignored. Whitespace characters could be optionally included or omitted virtually anywhere—between identifiers and reserved words, and even in the middle of identifiers and reserved words.

Fortran的最早版本是最早创建的一种编程语言,其设计目的是完全忽略所有空格。 几乎可以在标识符和保留字之间,甚至在标识符和保留字之间的任何位置,都可以选择包含或省略空白字符。

For example, if your Fortran code contained a variable named total, any of the following would be a valid statement to assign it the value 50:

例如,如果您的Fortran代码包含一个名为total的变量,则以下任何一项都是有效的语句,将其赋值为50

total = 50
to tal = 50
t o t a l=5 0
total = 50
to tal = 50
t o t a l=5 0

This was meant as a convenience, but in retrospect it is widely regarded as overkill. It often resulted in code that was difficult to read. Worse yet, it potentially led to code that did not execute correctly.

这样做是为了方便,但回想起来,它被普遍认为是过大的杀伤力。 它经常导致难以阅读的代码。 更糟糕的是,它可能导致代码无法正确执行。

Consider this tale from NASA in the 1960s. A Mission Control Center orbit computation program written in Fortran was supposed to contain the following line of code:

考虑一下1960年代NASA的故事。 用Fortran编写的Mission Control Center轨道计算程序应该包含以下代码行:

DO 10 I = 1,100
DO 10 I = 1,100

In the Fortran dialect used by NASA at that time, the code shown introduces a loop, a construct that executes a body of code repeatedly. (You will learn about loops in Python in two future tutorials on definite and indefinite iteration).

在当时NASA使用的Fortran方言中,所示代码引入了一个循环,即一种循环执行代码主体的构造。 (您将在以后的两个关于定和不定迭代的教程中学习Python中的循环)。

Unfortunately, this line of code ended up in the program instead:

不幸的是,这一行代码最终出现在程序中:

DO 10 I = 1.100
DO 10 I = 1.100

If you have a difficult time seeing the difference, don’t feel too bad. It took the NASA programmer a couple weeks to notice that there is a period between 1 and 100 instead of a comma. Because the Fortran compiler ignored whitespace, DO 10 I was taken to be a variable name, and the statement DO 10 I = 1.100 resulted in assigning 1.100 to a variable called DO10I instead of introducing a loop.

如果您很难看到差异,请不要感到难过。 NASA程序员花了几周的时间才注意到,它的间隔是1100而不是逗号。 因为Fortran编译器忽略空白,所以将DO 10 I视为变量名,并且语句DO 10 I = 1.100导致将1.100分配给名为DO10I的变量,而不引入循环。

Some versions of the story claim that a Mercury rocket was lost because of this error, but that is evidently a myth. It did apparently cause inaccurate data for some time, though, before the programmer spotted the error.

故事的某些版本声称汞火箭因该错误而丢失,但这显然是神话。 不过,在程序员发现错误之前,它确实确实导致了一段时间的数据不正确。

Virtually all modern programming languages have chosen not to go this far with ignoring whitespace.

几乎所有现代编程语言都选择不忽略空格而走得更远。

空格作为缩进 (Whitespace as Indentation)

There is one more important situation in which whitespace is significant in Python code. Indentation—whitespace that appears to the left of the first token on a line—has very special meaning.

还有另一种重要情况,其中空白在Python代码中很重要。 缩进-出现在一行中第一个标记左侧的空白-具有非常特殊的含义。

In most interpreted languages, leading whitespace before statements is ignored. For example, consider this Windows Command Prompt session:

在大多数解释语言中,语句前的空白将被忽略。 例如,考虑以下Windows命令提示符会话:

 C:Usersjohn>C:Usersjohn> echo foo
echo foo
foo

foo

C:Usersjohn>    C:Usersjohn>    echo foo
echo foo
foo
foo

Note: In a Command Prompt window, the echo command displays its arguments to the console, like the print() function in Python. Similar behavior can be observed from a terminal window in macOS or Linux.

注意:在命令提示符窗口中, echo命令将其参数显示到控制台,就像Python中的print()函数一样。 从macOS或Linux的终端窗口中可以观察到类似的行为。

In the second statement, four space characters are inserted to the left of the echo command. But the result is the same. The interpreter ignores the leading whitespace and executes the same command, echo foo, just as it does when the leading whitespace is absent.

在第二条语句中,在echo命令的左侧插入了四个空格字符。 但是结果是一样的。 解释器将忽略前导空格,并执行相同的命令echo foo ,就像不存在前导空格时一样。

Now try more or less the same thing with the Python interpreter:

现在,使用Python解释器或多或少尝试相同的事情:

Say what? Unexpected indent? The leading whitespace before the second print() statement causes a SyntaxError exception!

说什么? 意外缩进? 第二个print()语句之前的前导空格导致SyntaxError异常!

In Python, indentation is not ignored. Leading whitespace is used to compute a line’s indentation level, which in turn is used to determine grouping of statements. As yet, you have not needed to group statements, but that will change in the next tutorial with the introduction of control structures.

在Python中,缩进不会被忽略。 前导空格用于计算行的缩进级别,而缩进级别又用于确定语句的分组。 到目前为止,您还不需要对语句进行分组,但是在下一个教程中,随着控制结构的引入,这种情况将有所改变。

Until then, be aware that leading whitespace matters.

在此之前,请注意领先的空格很重要。

结论 (Conclusion)

This tutorial introduced you to Python program lexical structure. You learned what constitutes a valid Python statement and how to use implicit and explicit line continuation to write a statement that spans multiple lines. You also learned about commenting Python code, and about use of whitespace to enhance readability.

本教程向您介绍了Python程序的词法结构。 您了解了什么构成有效的Python 语句,以及如何使用隐式显式的行连续性编写跨越多行的语句。 您还了解了有关注释Python代码以及如何使用空格来增强可读性的知识。

Next, you will learn how to group statements into more complex decision-making constructs using conditional statements.

接下来,您将学习如何使用条件语句将语句分组为更复杂的决策结构。

翻译自: https://www.pybloggers.com/2018/09/structuring-python-programs/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值