3. An Informal Introduction to Python

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.

在下面的例子中,输入和输出的区别在于是否有提示(>>>和...):为了重复例子,当提示出现的时候,你需要在提示后面输入;对于解释器而言没有以提示符开始的行就是输出。注意在事例中一行的第二个提示符表示你需要输出一个空行;这在结束多行命令时应用。

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. 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中使用#符号作为注释的开始符,直到一行结束。注释可能出现在一行的开始或者跟在空格或者代码后,但是不会出现在一串文字中间。一串文字中间的#符号就是#符号,并不是注释。因为注释就是阐述代码,不会被python解释,所以他们可能在例子中被省略。

Some examples:

# this is the first commentspam = 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

Let’s try some simple Python commands. Start the interpreter and wait for the primary prompt, >>>. (It shouldn’t take long.)

让我们试试一些简单的python命令吧。启动解释器并等待第一个提示符>>>(出现提示符不会花费太久)。

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. For example:

解释器就像单个计算器:你可以输入一个表达式,解释器将会输出它的值。表达式语法非常简单:操作符+,-,*和/就和绝大部分其他语言一样工作(比如,Pascal或者C);可以使用(())圆括号分组。例如:

>>>

>>> 2 + 24>>> 50 - 5*620>>> (50 - 5*6) / 45.0>>> 8 / 5  # division always returns a floating point number1.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 typefloat. We will see more about numeric types later in the tutorial.

整数(比如2,4,20)有对应的数据类型int,小数部分(比如5.0,1.6)有对应的数据类型float。后续我们会在本指南中看到更多的数据类型。

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 float5.666666666666667>>>>>> 17 // 3  # floor division discards the fractional part5>>> 17 % 3  # the % operator returns the remainder of the division2>>> 5 * 3 + 2  # result * divisor + remainder17

除号/常常返回一个浮点数。为了整除并且获得结果的整数部分(丢弃任何的小数结果)你可以使用//操作符;为了计算余数,你可以使用%:

With Python, it is possible to use the ** operator to calculate powers 1:

>>>

>>> 5 ** 2  # 5 squared25>>> 2 ** 7  # 2 to the power of 7128

在python中,使用**操作符计算幂乘(阶乘):

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 * height900

If a variable is not “defined” (assigned a value), trying to use it will give you an error:

如果一个未定义的变量使用,那么会给出报错:

>>>

>>> n  # try to access an undefined variableTraceback (most recent call last):

  File "", line 1, in 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 - 114.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 * tax12.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.

这个变量对于用户需要作为只读变量。不能赋值给它——您将创建一个具有相同名称的独立局部变量,并用其magic(翻译出来不合适)的行为屏蔽内置变量。

In addition to int and float, Python supports other types of numbers, such as Decimal and Fraction. Python also has built-in support for complex numbers, and uses the j or J suffix to indicate the imaginary part (e.g. 3+5j).

除int和float之外,python支持其他的数据类型,比如Decimal和Fraction。Python也支持内置的复数(译者说,这是数学里面的复数,由实部和虚部组成),并使用j或者J后缀来表示虚构部分。

3.1.2. Strings

Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes ('...') or double quotes ("...") with the same result 2. \ can be used to escape quotes:

除了数字之外,python也可以使用多种方式操作字符串。使用单引号或者双引号引用字符串的效果一样。可以使用\符号来引用引号。(译者说,就是说当在字符串中有引号——无论单引号还是双引号,为了表示引号自身字符,非引号功能,可以在引号前面加\)

>>>

>>> '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 lineFirst 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:\someame>>> print(r'C:\some\name')  # note the r before the quoteC:\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 "", line 1

    prefix 'thon'

                ^SyntaxError: invalid syntax>>> ('un' * 3) 'ium'

  File "", 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, slicingallows you to obtain substring:

为了索引,需要支持分片。虽然索引是为了获取单个字符,但分片允许你包含子串(译者说,就是一串字符的一部分,比如python的子串可以是py,或者tho):

>>>

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

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:

注意,下标的起始位总是包含在内,结尾不包含。译者说,比如word[0:2],展开就是word[0],word[1]。没有word[2]!

这样的话,s[:i] + s[i:]就是s。

>>>

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

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.

分片索引有可用的默认值;省略的第一个索引默认是0,第二个省略的索引是分片字符串的长度。

>>>

>>> 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'

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. Then the right edge of the last character of a string of n characters has index n, for example:

记住切片工作原理的一种方法是将下标看作字符之间的指针,第一个字符的左边缘编号为0。那么一个n个字符的字符串的最后一个字符的右边缘下标n(译者说,其实最后一个是n-1),例如:

 +---+---+---+---+---+---+

 | 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. The slice from i to j consists of all characters between the edges labeled i and j, respectively.

这一行给定的数字是正数0-6,第二行给的是相应的复数下标。从i到j的分片包含了从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.

对于非负数索引,分片长度不同于索引,如果两者都在边界内。比如,word[1:3]的长度是2。(译者说,因为右边缘不包含,所以word[1:3]就是word[1]和word[2])

Attempting to use an index that is too large will result in an error:

如果企图使用过大的下标会导致错误:

>>>

>>> word[42]  # the word only has 6 charactersTraceback (most recent call last):

  File "", line 1, in 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. Therefore, assigning to an indexed position in the string results in an error:

Python字符串不可以改变,他们是不可变的。因此,给字符的指定下标位置赋值会导致错误:

>>>

>>> word[0] = 'J'Traceback (most recent call last):

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

  File "", line 1, in 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().

printf-style String Formatting

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. 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.

Python知道许多复合数据类型,用于将其他值组合在一起。最有用的就是列表,它可以写成方括号中逗号分隔值(项)的列表。列表可以包含不同类型的项,但是通常把类似的数据类型放在一起。

>>>

>>> 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 item1>>> 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 new (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. For instance, we can write an initial sub-sequence of the Fibonacci series as follows:

当然,我们可以使用python实现更复杂的任务,而非2+2。比如,我们写一个初始化的斐波拉切序列的子序列,如下:

>>>

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

This example introduces several new features.

这个列子介绍了几个新的特性。(译者说,这是小学数学吧,大家看看,很有名的一道数学题。内容就不翻译了)

[if !supportLists]· [endif]

The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 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.

[if !supportLists]· [endif]

[if !supportLists]· [endif]

The while loop executes as long as the condition (here: a < 10) remains true. In Python, like in C, any non-zero integer value is true; zero is false. 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).

[if !supportLists]· [endif]

[if !supportLists]· [endif]

The body of the loop is indented: indentation is Python’s way of grouping statements. 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. 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.

[if !supportLists]· [endif]

[if !supportLists]· [endif]

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. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this:

[if !supportLists]· [endif]

>>>

[if !supportLists]· [endif]

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

[if !supportLists]· [endif]

The keyword argument end can be used to avoid the newline after the output, or end the output with a different string:

[if !supportLists]· [endif]

>>>

[if !supportLists]· [endif]

>>> 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,

[if !supportLists]· [endif]

Footnotes

1

Since ** has higher precedence than -, -3**2 will be interpreted as -(3**2) and thus result in -9. To avoid this and get 9, you can use (-3)**2.

因为**的优先级高于-,所以-3**2将被理解为-(3**2),结果是-9。为了避免这个问题而得到9,你可以使用(-3)**2。

2

Unlike other languages, special characters such as \n have the same meaning with both single ('...') and double ("...") quotes. 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.

与其他语言不同,\n等特殊字符在单引号('…')和双引号("…")中具有相同的含义。两者之间唯一的区别是,在单引号中不需要转义(但是必须转义\'),反之亦然。

你可能感兴趣的:(3. An Informal Introduction to Python)