# 3. Python 简介

```# this is the first comment
SPAM = 1                 # and this is the second comment
# ... and now a third!
STRING = "# This is not a comment."
```

## 3.1. 将 Python 当做计算器

### 3.1.1. 数字

```>>> 2+2
4
>>> # This is a comment
... 2+2
4
>>> 2+2  # and a comment on the same line as code
4
>>> (50-5*6)/4
5
>>> # Integer division returns the floor:
... 7/3
2
>>> 7/-3
-3
```

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

```>>> x = y = z = 0  # Zero x, y and z
>>> x
0
>>> y
0
>>> z
0
```

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

```>>> 1j * 1J
(-1+0j)
>>> 1j * complex(0, 1)
(-1+0j)
>>> 3+1j*3
(3+3j)
>>> (3+1j)*3
(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)
```

```>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5
```

```>>> a=3.0+4.0j
>>> float(a)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can't convert complex to float; use abs(z)
>>> a.real
3.0
>>> a.imag
4.0
>>> abs(a)  # sqrt(a.real**2 + a.imag**2)
5.0
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can't convert complex to float; use abs(z)
```

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

### 3.1.2. 字符串

```>>> 'spam eggs'
'spam eggs'
>>> 'doesn\'t'
"doesn't"
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
```

Python 解释器按照字符串被输入的方式打印字符串结果：为了显示准确的值，字符串包含在成对的引号中，引号和其他特殊字符要用反斜线（ \ ）转译。 如果字符串只包含单引号（ ‘ ）而没有双引号（ ” ）就可以用双引号（ ” ）包围，反之用单引号（ ‘ ）包围。 再强调一下， print 语句可以生成可读性更好的输出。

```hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant."

print hello
```

```This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.
```

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

```hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."

print(hello)
```

```This is a rather long string containing\n\
several lines of text much as you would do in C.
```

```>>> word = 'Help' + 'A'
>>> word
'HelpA'
>>> '<' + word*5 + '>'
'<HelpAHelpAHelpAHelpAHelpA>'
```

```>>> 'str' 'ing'                   #  <-  This is ok
'string'
>>> 'str'.strip() + 'ing'   #  <-  This is ok
'string'
>>> 'str'.strip() 'ing'     #  <-  This is invalid
File "<stdin>", line 1, in ?
'str'.strip() 'ing'
^
SyntaxError: invalid syntax
```

```>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'
```

```>>> word[:2]    # The first two characters
'He'
>>> word[2:]    # Everything except the first two characters
'lpA'
```

```>>> word[0] = 'x'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'str' object does not support item assignment
>>> word[:1] = 'Splat'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'str' object does not support slice assignment
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'str' object does not support slice assignment
```

```>>> 'x' + word[1:]
'xelpA'
>>> 'Splat' + word[4]
'SplatA'
```

```>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'
```

Python 能够优雅地处理那些没有意义的切片索引：一个过大的索引值（即下标值大于字符串实际长度）将被字符串实际长度所代替，当上边界比下边界大时（即切片左值大于右值）就返回空字符串。

```>>> word[1:100]
'elpA'
>>> word[10:]
''
>>> word[2:1]
''
```

```>>> word[-1]     # The last character
'A'
>>> word[-2]     # The last-but-one character
'p'
>>> word[-2:]    # The last two characters
'pA'
>>> word[:-2]    # Everything except the last two characters
'Hel'
```

```>>> word[-0]     # (since -0 equals 0)
'H'
```

```>>> word[-100:]
'HelpA'
>>> word[-10]    # error
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: string index out of range
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: string index out of range
```

``` +---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0   1   2   3   4   5
-5  -4  -3  -2  -1```

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

### 3.1.3. 关于 Unicode

Unicode 的先进之处在于为每一种现代或古代使用的文字系统中出现的每一个字符都提供了统一的序列号。之前，文字系统中的字符只能有 256 种可能的顺序。通过代码页分界映射。文本绑定到映射文字系统的代码页。这在软件国际化的时候尤其麻烦 （通常写作 i18n —— 'i' + 18 个字符 + 'n' ）。Unicode 解决了为所有的文字系统设置一个独立代码页的难题。

```>>> u'Hello World !'
u'Hello World !'
```

```>>> u'Hello\u0020World !'
u'Hello World !'
```

```>>> ur'Hello\u0020World !'
u'Hello World !'
>>> ur'Hello\\u0020World !'
u'Hello\\\\u0020World !'
```

```>>> u"abc"
u'abc'
>>> str(u"abc")
'abc'
>>> u"盲枚眉"
u'\xe4\xf6\xfc'
>>> str(u"盲枚眉")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
```

```>>> u"盲枚眉".encode('utf-8')
'\xc3\xa4\xc3\xb6\xc3\xbc'
```

```>>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8')
u'\xe4\xf6\xfc'
```

### 3.1.4. 列表

Python 有几个 复合 数据类型，用于表示其它的值。最通用的是 list (列表) ，它可以写作中括号之间的一列逗号分隔的值。列表的元素不必是同一类型。

```>>> a = ['spam', 'eggs', 100, 1234]
>>> a
['spam', 'eggs', 100, 1234]
```

```>>> a[0]
'spam'
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>> 3*a[:3] + ['Boo!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']
```

```>>> a[:]
['spam', 'eggs', 100, 1234]
```

```>>> a
['spam', 'eggs', 100, 1234]
>>> a[2] = a[2] + 23
>>> a
['spam', 'eggs', 123, 1234]
```

```>>> # Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # Remove some:
... a[0:2] = []
>>> a
[123, 1234]
>>> # Insert some:
... a[1:1] = ['bletch', 'xyzzy']
>>> a
[123, 'bletch', 'xyzzy', 1234]
>>> # Insert (a copy of) itself at the beginning
>>> a[:0] = a
>>> a
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
>>> # Clear the list: replace all items with an empty list
>>> a[:] = []
>>> a
[]
```

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

```>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
>>> p[1][0]
2
```

```>>> p[1].append('xtra')
>>> p
[1, [2, 3, 'xtra'], 4]
>>> q
[2, 3, 'xtra']
```

## 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；0 是 false。判断条件也可以是字符串或列表，实际上可以是任何序列；所有长度不为零的是 true ，空序列是 false。示例中的测试是一个简单的比较。标准比较操作符与 C 相同： < （小于）， > （大于）， == （等于）， <= （小于等于）， >= （大于等于）和 != （不等于）。

• 循环 缩进 的：缩进是 Python 组织語句的方法。 Python (还) 不提供集成的行编辑功能，所以你要为每一个缩进行输入 TAB 或空格。实践中建议你找个文本编辑来录入复杂的 Python 程序，大多数文本编辑器提供自动缩进。交互式录入复合语句时，必须在最后输入一个空行来标识结束（因为解释器没办法猜测你输入的哪一行是最后一行），需要注意的是同一个语句块中的每一行必须缩进同样数量的空白。

• 关键字 print 语句输出给定表达式的值。它控制多个表达式和字符串输出为你想要字符串（就像我们在前面计算器的例子中那样）。字符串打印时不用引号包围，每两个子项之间插入空间，所以你可以把格式弄得很漂亮，像这样

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

用一个逗号结尾就可以禁止输出换行:

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