3. Python 简介 Python v3.4.3 官方教程
2016-01-11 17:41:40

`# 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. 将 Python 当做计算器

### 3.1.1. 数字

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

`>>> 17 / 3 # classic pision returns a float 5.666666666666667 >>> >>> 17 // 3 # floor pision discards the fractional part 5 >>> 17 % 3 # the % operator returns the remainder of the pision 2 >>> 5 * 3 + 2 # result * pisor + remainder 17 `

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

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

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

`>>> 3 * 3.75 / 1.5 7.5 >>> 7.0 / 2 3.5 `

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

### 3.1.2. 字符串

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

`>>> '"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 line First line. Second line. `

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

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

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

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

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

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

`>>> prefix + 'thon' 'Python' `

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

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

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

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

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

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

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

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

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

Python 字符串不可以改变—它们是不可变的因此，赋值给字符串索引的位置会导致错误：

`>>> word[0] = 'J'  ... TypeError: 'str' object does not support item assignment >>> word[2:] = 'py'  ... TypeError: 'str' object does not support item assignment `

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

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

Text Sequence Type — strStrings are examples of sequence types, and support the common operations supported by such types.String MethodsStrings support a large number of methods for basic transformations and searching.String FormattingInformation about string formatting with str.format() is described here.printf-style String FormattingThe old formatting operations invoked when strings and Unicode strings are the left operand of the % operator are described in more detail here.

### 3.1.3. 列表

Python 有几个 复合 数据类型，用来组合其他的值。最有用的是 列表，可以写成中括号中的一列用逗号分隔的值。列表可以包含不同类型的元素，但是通常一个列表中的所有元素都拥有相同的类型。

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

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

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

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

`>>> 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] `

`>>> 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] `

`>>> 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 [] `

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

`>>> 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. 编程第一步

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

• 第一行包括了一个多重赋值：变量ab同时获得新的值 0 和 1。最后一行又这样使用了一次，说明等号右边的表达式在赋值之前首先被完全解析。右侧表达式是从左到右计算的。

• 只要条件（这里是 b < 10）为 true，while循环反复执行。在 Python 中，和 C 一样，任何非零整数值都为 true；零为 false。循环条件也可以是一个字符串或者列表，实际上可以是任何序列；长度不为零的序列为 true，空序列为 false。示例中使用的测试是一个简单的比较。标准比较运算符与 C 的写法一样：<（小于）， > （大于）， = = (等于)， < = （小于或等于）， > = （大于或等于） 和! = （不等于）。

• 循环 是缩进 的：缩进是 Python 分组语句的方式。交互式输入时，你必须为每个缩进的行输入一个 tab 或（多个）空格。实践中你会用文本编辑器来编写复杂的 Python 程序；所有差不多的文本编辑器都有自动缩进的功能。交互式输入复合语句时，最后必须跟随一个空行来表示结束（因为解析器无法猜测你什么时候已经输入最后一行）。注意基本块内的每一行必须按相同的量缩进。

• print()函数输出传给它的参数的值。与仅仅输出你想输出的表达式不同（就像我们在前面计算器的例子中所做的），它可以输出多个参数、浮点数和字符串。打印出来的字符串不包含引号，项目之间会插入一个空格，所以你可以设置漂亮的格式，像这样：

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

关键字参数 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, `

 [1] 因乘幂运算 ** 比取负运算 -有更高的优先级, 因此-3**2 将被解释为 -(3**2) 所以结果会得到-9. 为避免这种结果，而得到想要的结果 9, 你可以使用 (-3)**2.
 [2] 不同于其他语言的，特殊字符如 \n 在单引号 ('...') 和双引号 ("...") 之内是一样的. 两者之间的唯一区别是单引号内不需要对双引号 " 转义(但你要转义单引号 \') 反之亦然.