# 第三章 基本使用

## 3.1 用Python作计算器使用

>>> 2+2

4

>>> # 这是一个注释
... 2+2
4
>>> 2+2  # 和代码在同一行的注释
4
>>> (50-5*6)/4
5
>>> # 整数除法得下面的整数
... 7/3
2
>>> 7/-3
-3
>>>

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

>>> x = y = z = 0  # 把 x, y 和 z赋零

>>> x
0
>>> y
0
>>> z
0
>>>

Python完全支持浮点数，混合类型的运算会把整数先转换成浮点数：

>>> 4 * 2.5 / 3.3
3.0303030303
>>> 7.0 / 2
3.5
>>>

Python也提供了复数，方法是用j和J作为虚数单位，如1+1j，3.14e-10j，等等。

## 3.2. 字符串

Python除处理数字外还可以处理字符串，字符串用单撇号或双撇号包裹：
>>> '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.'
>>>

字符串可以用+号连接起来，用*号重复：

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

Python没有单独的字符数据类型，一个字符就是长度为一的字符串。象在Icon语言中那样，可以用片段(slice)记号来指定子串，片段即用冒号隔开的两个下标。

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

>>> word[:2]    # 前两个字符
'He'
>>> word[2:]    # 除前两个字符串外的部分
'lpA'
>>>

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

'HelpA'
>>>

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

>>> word[-1]     # 最后一个字符
'A'
>>> word[-2]     # 倒数第二个字符
'p'
>>> word[-2:]    # 最后两个字符
'pA'
>>> word[:-2]    # 除最后两个字符外的部分
'Hel'
>>>

>>> word[-0]     # (因为 -0 等于 0)
'H'
>>>

>>> word[-100:]
'HelpA'
>>> word[-10]    # 错误
Traceback (innermost last):
File "<stdin>", line 1
IndexError: string index out of range

>>>

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

内置函数len()返回字符串的长度：

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

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./n"
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 = """

This string is bounded by triple double quotes (3 times ").
Unescaped newlines in the string are retained, though         it is still possible/nto use all normal escape sequences.

Whitespace at the beginning of a line is
significant.  If you need to include three opening quotes
you have to escape at least one of them, e.g. /""".

This string ends in a newline.
"""

## 3.3 列表

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

>>> # 替换若干项:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # 去掉若干项:
... a[0:2] = []
>>> a
[123, 1234]
>>> # 插入若干项:
... a[1:1] = ['bletch', 'xyzzy']
>>> a
[123, 'bletch', 'xyzzy', 1234]
>>> a[:0] = a     # 在开头插入自身
>>> 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')     # 列表方法
>>> p
[1, [2, 3, 'xtra'], 4]
>>> q
[2, 3, 'xtra']
>>>

## 3.4 编程初步

Python当然不是只能用来把两个数加到一起，它可以完成很复杂的工作。例如，我们可以写出Fibonacci序列的开始几个：

>>> # Fibonacci 序列:
... # 两个元素的和定义下一个
... a, b = 0, 1
>>> while b < 10:
...       print b
...       a, b = b, a+b
...
1
1
2
3
5
8
>>>

while循环当循环条件(这里即: b < 10)成立时不断执行。在Python中和C中一样，非零整数值为真值，零为假值。条件也可以是字符串或列表或任何序列，长度为非零的为真，空序列为假。例子中所用的是一个简单比较。标准的比较算符和C一样：

<, >, ==, <=, >= 和 !=。

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

Python还提供了和C语言一样的printf格式的输出方式，这是用%实现的，左边是格式，如：

>>> print 'The value of 1/7 is approximately %5.3f.' % 0.142857
The value of 1/7 is approximately 0.143.
>>>

>>> print "Name: %-10s  Age: %3d" % ("White", 31)
Name: White      Age:  31

• 本文已收录于以下专栏：

举报原因： 您举报文章：Python编程入门(2) 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)