3. An Informal Introduction to PythonPython的非正式介绍

In the following examples, input and output are distinguished by the presence or absence of prompts (>>> and ): to repeat the example, you must type everything after the prompt, when the prompt appears; lines that do not begin with a prompt are output from the interpreter. 在以下示例中,输入和输出通过提示的存在与否来区分(>>>...):要重复该示例,当提示出现时,必须在提示后键入所有内容;不以提示符开头的行从解释器输出。Note that a secondary prompt on a line by itself in an example means you must type a blank line; this is used to end a multi-line command.请注意,在示例中,行上的辅助提示本身意味着您必须键入空行;这用于结束多行命令。

You can toggle the display of prompts and output by clicking on >>> in the upper-right corner of an example box. 您可以通过单击示例框右上角的>>>来切换提示和输出的显示。If you hide the prompts and output for an example, then you can easily copy and paste the input lines into your interpreter.如果隐藏示例的提示和输出,则可以轻松地将输入行复制并粘贴到解释器中。

Many of the examples in this manual, even those entered at the interactive prompt, include comments. 本手册中的许多示例,甚至是在交互式提示下输入的示例,都包含注释。Comments in Python start with the hash character, #, and extend to the end of the physical line. Python中的注释以散列字符#开头,并延伸到物理行的末尾。A comment may appear at the start of a line or following whitespace or code, but not within a string literal. 注释可能出现在行首或空格或代码之后,但不能出现在字符串文字中。A hash character within a string literal is just a hash character. 字符串文字中的哈希字符只是一个哈希字符。Since comments are to clarify code and are not interpreted by Python, they may be omitted when typing in examples.由于注释是为了澄清代码,而不是由Python解释,所以在示例中键入时可能会忽略注释。

Some examples:例如:

# this is the first comment
spam = 1 # and this is the second comment
# ... and now a third!
text = "# This is not a comment because it's inside quotes."

3.1. Using Python as a Calculator使用Python作为计算器

Let’s try some simple Python commands. 让我们试试一些简单的Python命令。Start the interpreter and wait for the primary prompt, >>>. 启动解释器并等待主提示>>>(It shouldn’t take long.)(这不会花很长时间。)

3.1.1. Numbers数字

The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. 解释器就像一个简单的计算器:你可以在它上面输入一个表达式,它会写下值。Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages (for example, Pascal or C); parentheses (()) can be used for grouping. 表达式语法很简单:运算符+-*/的工作方式与大多数其他语言(例如,Pascal或C)一样;括号(())可用于分组。For example:例如:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5 # division always returns a floating point number
1.6

The integer numbers (e.g. 2, 4, 20) have type int, the ones with a fractional part (e.g. 5.0, 1.6) have type float. 整数(如2420)的类型为int,小数部分(如5.01.6)的类型为floatWe will see more about numeric types later in the tutorial.我们将在本教程后面看到更多关于数字类型的内容。

Division (/) always returns a float. 除法(/)总是返回一个浮点数。To do floor division and get an integer result (discarding any fractional result) you can use the // operator; to calculate the remainder you can use %:要进行向下取整分割并获得整数结果(丢弃任何分数结果),可以使用//运算符;要计算余数,可以使用%

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3 # floor division discards the fractional part
5
>>> 17 % 3 # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2 # floored quotient * divisor + remainder
17

With Python, it is possible to use the ** operator to calculate powers 1:使用Python,可以使用**运算符计算幂1

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7 # 2 to the power of 7
128

The equal sign (=) is used to assign a value to a variable. 等号(=)用于为变量赋值。Afterwards, no result is displayed before the next interactive prompt:之后,在下一个交互式提示之前不会显示任何结果:

>>> width = 20
>>> height = 5 * 9
>>> width * height
900

If a variable is not “defined” (assigned a value), trying to use it will give you an error:如果变量未“定义”(指定值),尝试使用它会出现错误:

>>> n  # try to access an undefined variable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:完全支持浮点运算;具有混合类型操作数的运算符将整数操作数转换为浮点:

>>> 4 * 3.75 - 1
14.0

In interactive mode, the last printed expression is assigned to the variable _. 在交互模式下,最后一个打印的表达式被指定给变量_This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:这意味着当您使用Python作为桌面计算器时,继续计算会更容易,例如:

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06

This variable should be treated as read-only by the user. 用户应将此变量视为只读变量。Don’t explicitly assign a value to it — you would create an independent local variable with the same name masking the built-in variable with its magic behavior.不要显式地给它赋值——你会创建一个同名的独立局部变量,用它的神奇行为屏蔽内置变量。

In addition to int and float, Python supports other types of numbers, such as Decimal and Fraction. 除了intfloat之外,Python还支持其他类型的数字,比如DecimalFractionPython also has built-in support for complex numbers, and uses the j or J suffix to indicate the imaginary part (e.g. 3+5j).Python还内置了对复数的支持,并使用jJ后缀来表示虚部(例如3+5j)。

3.1.2. Strings字符串

Besides numbers, Python can also manipulate strings, which can be expressed in several ways. 除了数字,Python还可以操作字符串,字符串可以用几种方式表示。They can be enclosed in single quotes ('...') or double quotes ("...") with the same result 2. 它们可以用单引号('...')或双引号("...")括起来同样的结果2。\ can be used to escape quotes:可用于转义引号:

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t' # use \' to escape the single quote...
"doesn't"
>>> "doesn't" # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'

In the interactive interpreter, the output string is enclosed in quotes and special characters are escaped with backslashes. 在交互式解释器中,输出字符串用引号括起来,特殊字符用反斜杠转义。While this might sometimes look different from the input (the enclosing quotes could change), the two strings are equivalent. 虽然这有时看起来可能与输入不同(括起来的引号可能会改变),但这两个字符串是等效的。The string is enclosed in double quotes if the string contains a single quote and no double quotes, otherwise it is enclosed in single quotes. 如果字符串包含单引号且没有双引号,则该字符串将用双引号括起来,否则将用单引号括起来。The print() function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters:print()函数的作用是:省略引号,打印转义字符和特殊字符,从而产生更可读的输出:

>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print('"Isn\'t," they said.')
"Isn't," they said.
>>> s = 'First line.\nSecond line.' # \n means newline
>>> s # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s) # with print(), \n produces a new line
First line.
Second line.

If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote:如果不希望以\开头的字符被解释为特殊字符,可以使用原始字符串,方法是在第一个引号前添加一个r

>>> print('C:\some\name')  # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name') # note the r before the quote
C:\some\name

String literals can span multiple lines. 字符串文字可以跨越多行。One way is using triple-quotes: """...""" or '''...'''. 一种方法是使用三重引号:"""..."""或者'''...'''End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line. 行尾自动包含在字符串中,但可以通过在行尾添加\来防止这种情况。The following example:下面是一个例子:

print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")

produces the following output (note that the initial newline is not included):生成以下输出(请注意,不包括初始换行):

Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to

Strings can be concatenated (glued together) with the + operator, and repeated with *:字符串可以用+运算符连接(粘在一起),并用*

>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'

Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated.相邻的两个或多个字符串文字(即括在引号之间的文字)会自动连接起来。

>>> 'Py' 'thon'
'Python'

This feature is particularly useful when you want to break long strings:当您想要断开长字符串时,此功能特别有用:

>>> text = ('Put several strings within parentheses '
... 'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'

This only works with two literals though, not with variables or expressions:但这只适用于两个文本,而不适用于变量或表达式:

>>> prefix = 'Py'
>>> prefix 'thon' # can't concatenate a variable and a string literal
File "<stdin>", line 1
prefix 'thon'
^
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
File "<stdin>", line 1
('un' * 3) 'ium'
^
SyntaxError: invalid syntax

If you want to concatenate variables or a variable and a literal, use +:如果要连接变量或变量与文字,请使用+

>>> prefix + 'thon'
'Python'

Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:可以为字符串编制索引(下标),第一个字符的索引为0。没有单独的字符类型;一个字符就是一个大小为1的字符串:

>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'

Indices may also be negative numbers, to start counting from the right:指数也可以是负数,从右边开始计算:

>>> word[-1]  # last character
'n'
>>> word[-2] # second-last character
'o'
>>> word[-6]
'P'

Note that since -0 is the same as 0, negative indices start from -1.请注意,由于-0与0相同,负指数从-1开始。

In addition to indexing, slicing is also supported. 除了索引,还支持切片While indexing is used to obtain individual characters, slicing allows you to obtain substring:虽然索引用于获取单个字符,但切片允许您获取子字符串:

>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.切片索引具有有用的默认值;省略的第一个索引默认为零,省略的第二个索引默认为被切片的字符串的大小。

>>> word[:2]   # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:] # characters from position 4 (included) to the end
'on'
>>> word[-2:] # characters from the second-last (included) to the end
'on'

Note how the start is always included, and the end always excluded. 请注意始终包含开始,而始终排除结束。This makes sure that s[:i] + s[i:] is always equal to s:这确保了s[:i] + s[i:]始终等于s:

>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'

One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. 记住切片工作原理的一种方法是将索引视为指向字符之间,第一个字符的左边缘编号为0。Then the right edge of the last character of a string of n characters has index n, for example:然后,n个字符字符串的最后一个字符的右边缘具有索引n,例如:

 +---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1

The first row of numbers gives the position of the indices 0…6 in the string; the second row gives the corresponding negative indices. 第一行数字给出了索引06在字符串中的位置;第二行给出了相应的负指数。The slice from i to j consists of all characters between the edges labeled i and j, respectively.ij的切片由分别标记为i和j的边之间的所有字符组成。

For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. 对于非负指数,如果两个指数都在范围内,则切片的长度是指数的差值。For example, the length of word[1:3] is 2.例如,单词[1:3]的长度是2。

Attempting to use an index that is too large will result in an error:尝试使用太大的索引将导致错误:

>>> word[42]  # the word only has 6 characters
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range

However, out of range slice indexes are handled gracefully when used for slicing:但是,当用于切片时,会优雅地处理超出范围的切片索引:

>>> word[4:42]
'on'
>>> word[42:]
''

Python strings cannot be changed — they are immutable. Python字符串不能更改——它们是不可变的Therefore, assigning to an indexed position in the string results in an error:因此,在字符串中指定索引位置会导致错误:

>>> word[0] = 'J'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

If you need a different string, you should create a new one:如果需要其他字符串,应创建一个新字符串:

>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'

The built-in function len() returns the length of a string:内置函数len()返回字符串的长度:

>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34

See also另见

Text Sequence Type文本序列类型 — str

Strings are examples of sequence types, and support the common operations supported by such types.字符串是序列类型的示例,支持此类类型支持的常见操作。

String Methods字符串方法

Strings support a large number of methods for basic transformations and searching.字符串支持大量用于基本转换和搜索的方法。

Formatted string literals格式化字符串文本

String literals that have embedded expressions.具有嵌入表达式的字符串文本。

Format String Syntax格式字符串语法

Information about string formatting with str.format().详解使用str.format()设置字符串格式。

printf-style String Formattingprintf样式字符串格式

The old formatting operations invoked when strings are the left operand of the % operator are described in more detail here.这里更详细地描述了当字符串是%运算符的左操作数时调用的旧格式化操作。

3.1.3. Lists列表

Python knows a number of compound data types, used to group together other values. Python知道许多复合数据类型,用于将其他值组合在一起。The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. 最通用的是列表,它可以写为方括号之间逗号分隔的值(项)列表。Lists might contain items of different types, but usually the items all have the same type.列表可能包含不同类型的项,但通常所有项都具有相同的类型。

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

Like strings (and all other built-in sequence types), lists can be indexed and sliced:与字符串(以及所有其他内置序列类型)一样,列表可以被索引和切片:

>>> squares[0]  # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:] # slicing returns a new list
[9, 16, 25]

All slice operations return a new list containing the requested elements. 所有切片操作都会返回一个包含请求元素的新列表。This means that the following slice returns a shallow copy of the list:这意味着以下切片将返回列表的浅层副本

>>> squares[:]
[1, 4, 9, 16, 25]

Lists also support operations like concatenation:列表还支持连接等操作:

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content:不可变的字符串不同,列表是一种可变类型,也就是说,可以更改其内容:

>>> cubes = [1, 8, 27, 65, 125]  # something's wrong here
>>> 4 ** 3 # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64 # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]

You can also add new items at the end of the list, by using the append() method (we will see more about methods later):您还可以使用append()方法在列表末尾添加新项(我们将在后面看到有关方法的更多信息):

>>> cubes.append(216)  # add the cube of 6
>>> cubes.append(7 ** 3) # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:也可以分配到切片,这甚至可以更改列表的大小或完全清除列表:

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

The built-in function len() also applies to lists:内置函数len()也适用于列表:

>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4

It is possible to nest lists (create lists containing other lists), for example:可以嵌套列表(创建包含其他列表的列表),例如:

>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

3.2. First Steps Towards Programming编程的第一步

Of course, we can use Python for more complicated tasks than adding two and two together. 当然,我们可以使用Python来完成更复杂的任务,而不是将二和二相加。For instance, we can write an initial sub-sequence of the Fibonacci series as follows:例如,我们可以写出斐波那契级数的初始子序列,如下所示:

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while a < 10:
... print(a)
... a, b = b, a+b
...
0
1
1
2
3
5
8

This example introduces several new features.本例介绍了几个新特性。

  • The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. 第一行包含多个赋值:变量ab同时获得新值0和1。On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. 在最后一行中,再次使用了这一点,表明在任何赋值之前,都首先对右侧的表达式求值。The right-hand side expressions are evaluated from the left to the right.右侧表达式从左到右求值。

  • The while loop executes as long as the condition (here: a < 10) remains true. 只要条件(此处:a<10)保持为真,while循环就会执行。In Python, like in C, any non-zero integer value is true; zero is false. 在Python中,就像在C中一样,任何非零整数值都是真的;零是假的。The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. 条件也可以是字符串或列表值,实际上是任何序列;任何长度非零的都是真的,空序列都是假的。The test used in the example is a simple comparison. 示例中使用的测试是一个简单的比较。The standard comparison operators are written the same as in C: < (less than), > (greater than), == (equal to), <= (less than or equal to), >= (greater than or equal to) and != (not equal to).标准比较运算符的编写方式与C中的相同:<(小于),>(大于),==(等于),<=(小于或等于),>=(大于或等于)和!=(不等于)。

  • The body of the loop is indented: indentation is Python’s way of grouping statements. 循环的主体缩进的:缩进是Python对语句进行分组的方式。At the interactive prompt, you have to type a tab or space(s) for each indented line. 在交互式提示下,必须为每一条缩进的行键入一个制表符或空格。In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. 实际上,您将使用文本编辑器为Python准备更复杂的输入;所有像样的文本编辑器都有自动缩进功能。When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). 当以交互方式输入复合语句时,它后面必须有一个空行以指示完成(因为解析器无法猜测您何时键入了最后一行)。Note that each line within a basic block must be indented by the same amount.请注意,基本块中的每一行必须缩进相同的数量。

  • The print() function writes the value of the argument(s) it is given. It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple arguments, floating point quantities, and strings. print()函数的作用是:写入给定参数的值。它在处理多个参数、浮点量和字符串的方式上不同于只编写想要编写的表达式(就像我们在前面的计算器示例中所做的那样)。Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this:字符串打印时不带引号,项目之间插入空格,因此可以很好地格式化内容,如下所示:

    >>> i = 256*256
    >>> print('The value of i is', i)
    The value of i is 65536

    The keyword argument end can be used to avoid the newline after the output, or end the output with a different string:关键字参数end可用于避免输出后的换行符,或使用不同的字符串结束输出:

    >>> a, b = 0, 1
    >>> while a < 1000:
    ... print(a, end=',')
    ... a, b = b, a+b
    ...
    0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

Footnotes

1

Since ** has higher precedence than -, -3**2 will be interpreted as -(3**2) and thus result in -9. 因为**的优先级高于-,所以-3**2将被解释为-(3**2),因此结果为-9To avoid this and get 9, you can use (-3)**2.要避免这种情况并获得9,可以使用(-3)**2

2

Unlike other languages, special characters such as \n have the same meaning with both single ('...') and double ("...") quotes. 与其他语言不同,像\n这样的特殊字符对单引号('...')和双引号("...")具有相同的含义。The only difference between the two is that within single quotes you don’t need to escape " (but you have to escape \') and vice versa.两者之间唯一的区别是,在单引号中,你不需要转义"(但你必须转义\'),反之亦然。