[Python教程]3.一份非正式的Python教程

来源:互联网 发布:大数据专业研究生排名 编辑:程序博客网 时间:2024/06/05 13:25

3. An Informal Introduction to Python

一份非正式的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解析。

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

3.1把Python当计算器用

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

3.1.1.数字

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:
解释器表现的像个简单的计算器:你可以输入表达式,结果会被返回。+-*/这些操作符就和其他语言的一样。

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

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 "<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:
完全支持浮点数,混合运算会把整型转换为浮点型:

>>>>>> 3 * 3.75 / 1.57.5>>> 7.0 / 23.5

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.
这个变量对于用户是只读的,不要尝试去给他赋值。你可以创建一个同名的独立的本地变量屏蔽内置变量的魔术般的特征。

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).
不只是整型和浮点型,Python支持其他数字类型。像小数和分数。Python也支持复数,使用j或者J标志虚部。

3.1.2. Strings

3.1.2. 字符串

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," he said.''"Yes," he said.'>>> "\"Yes,\" he said."'"Yes," he said.'>>> '"Isn\'t," she said.''"Isn\'t," she 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," she said.''"Isn\'t," she said.'>>> print('"Isn\'t," she said.')"Isn't," she 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 only works with two literals though, not with variables or expressions:
上面的特征只对字符串有用,对变量不起作用:

>>>>>> prefix = 'Py'>>> prefix 'thon'  # can't concatenate a variable and a string literal  ...SyntaxError: invalid syntax>>> ('un' * 3) 'ium'  ...SyntaxError: invalid syntax

If you want to concatenate variables or a variable and a literal, use +:
如果想连接变量和字符串,用+号。

>>>>>> prefix + '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.'

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。Python没有单独的字符类型,一个字符就是一个长度为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'

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总是等于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,第二个默认是字符串的长度(最后一个字符的下标+1)。

>>>>>> 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 ,例如:

+—+—+—+—+—+—+
|-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的下标,第二行是负值下标。切片就是下标之间的字符。

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。
Attempting to use a index that is too large will result in an error:
下标越界会导致错误。

>>>>>> word[42]  # the word only has 6 charactersTraceback (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. Therefore, assigning to an indexed position in the string results in an error:
Python的字符串不可以被改变,对字符串的元素赋值会导致错误。

>>>>>> word[0] = 'J'  ...TypeError: 'str' object does not support item assignment>>> word[2:] = 'py'  ...TypeError: 'str' object does not support item assignmentIf 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

3.1.3. Lists

3.1.3列表

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.
巴拉巴拉巴拉。。。下面开始介绍列表:

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

Like strings (and all other built-in sequence type), 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

3.2.编程第一步

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完成更加复杂的任务。比如一个斐波拉契数列程序:

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

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. 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.
第一行包含了一个多重赋值:变量a,b被分别赋值0和1。最后一行又用了一次。右手边的表达式会在赋值前计算好,然后从左到右依次赋值。

The while loop executes as long as the condition (here: b < 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).
只要条件(b<10)为真,while循环就会被执行。在Python里,像在C里一样,所有的非0值就是真,0是假。条件也可以是字符串或者列表。事实上任何长度非0的序列都是真。空序列是假。标准比较运算符和C语言的一样:<,>,==,<=,>=,!=。

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.
循环体是缩进的,缩进是python区分代码块的方式。在交互式提示符下,你必须按下tab键或者空格键去缩进一行。事实上你应该使用一个文本编辑器来进行复杂输入。一般的文本编辑器都有自动缩进功能。在交互模式下输入复合语句时,结尾要加一个空行(因为解释器不能猜测什么时候你输入完成)。注意一个代码块每行缩进量要一致。
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:
print()函数可以输出给定参数的值。和简单输出你想要的值不同,它可以处理多个参数。

>>>>>> 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 b < 1000:...     print(b, end=',')...     a, b = b, a+b...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. To avoid this and get 9, you can use (-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在’…‘和“…”里的意义是一样的。’‘和“”的区别在于在’‘里不需对“用转义符号但是要对’用(\’)反之亦然。 ↩
0 0
原创粉丝点击