?

# ? 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

c一样，等号（“=”）用于给变量赋值。被分配的值是只读的。

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

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

Python完全支持浮点数，不同类型的操作数混在一起时，操作符会把整型转化为浮点数。

>>> 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 "", line 1, in ?
TypeError: can't convert complex to float; use e.g. abs(z)
>>> a.real
3.0
>>> a.imag
4.0
>>> abs(a)  # sqrt(a.real**2 + a.imag**2)
5.0
>>>

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

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.

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.

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

produces the following output:

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

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

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

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

>>> word[:2]    # The first two characters
'He'
>>> word[2:]    # All but the first two characters
'lpA'

C字符串不同，Python字符串不能改写。按字符串索引赋值会产生错误。

>>> word[0] = 'x'
Traceback (most recent call last):
File "", line 1, in ?
TypeError: object doesn't support item assignment
>>> word[:1] = 'Splat'
Traceback (most recent call last):
File "", line 1, in ?
TypeError: object doesn't support slice assignment

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

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

>>> 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]    # All but the last two characters
'Hel'

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

>>> word[-100:]
'HelpA'
>>> word[-10]    # error
Traceback (most recent call last):
File "", 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 字符串

Python2.0开始，程序员们可以使用一种新的数据类型来存储文本数据：Unicode 对象。它可以用于存储多种Unicode数据（请参阅 http://www.unicode.org/ ），并且，通过必要时的自动转换，它可以与现有的字符串对象良好的结合。

Unicode针对现代和旧式的文本中所有的字符提供了一个序列。以前，字符只能使用256个序号，文本通常通过绑定代码页来与字符映射。这很容易导致混乱，特别是软件的国际化（internationalization－－通常写做“i18n－－“i”+18 characters +“n”）。Unicode通过为所有字符定义一个统一的代码页解决了这个问题。

Python中定义一个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 "", 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 已经有了几个复合数据类型，用于组织其它的值。最通用的是链表，它写为中括之间用逗号分隔的一列值（子项），链表的子项不一定是同一类型的值。

>>> 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] + ['Boe!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']

>>> 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]
>>> a[:0] = a     # Insert (a copy of) itself at the beginning
>>> a
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]

>>> len(a)
8

>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
>>> p[1][0]
2
>>> p[1].append('xtra')     # See section 5.1
>>> 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同时被赋值为01。最后一行又一次使用了这种技术，证明了在赋值之前表达式右边先进行了运算。右边的表达式从左到右运算。

• while循环运行在条件为真时执行。在Python中，类似于C任何非零值为真，零为假。 这个条件也可以用于字符串或链表，事实上于对任何序列类型，长度非零时为真，空序列为假。示例所用的是一个简单的比较。标准的比较运算符写法和C相同： < （小于），> （大于），== （等于），<= （小于等于），>=（大于等于）和!= （不等于）

• 循环体是缩进的：缩进是Python对语句分组的方法。 Python仍没有提供一个智能编辑功能所以你要在每一个缩进行输入一个tab或（一个或多个）空格。 实际上你可能会准备更为复杂的文本编辑器来编写你的Python程序，大多数文本编辑器都提供了自动缩进功能。交互式的输入一个复杂语句时，需要用一个空行表示完成（因为解释器没办法猜出你什么时候输入最后一行）。需要注意的是每一行都要有相同的空字符来标识这是同一个语句块。

• print语句打印给定表达式的值。它与你仅仅输入你需要的表达式（就像前面的计算器示例）不同，它可以同时输出多个表达式。字符串输出时没有引号，各项之间用一个空格分开，你可以很容易区分它们，如下所示：

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

print语句末尾的逗号避免了输出中的换行：

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

需要注意的是，如果最后一行仍没有写完，解释器会在它打印下一个命令时插入一个新行。

0 0