下面的示例通过是否出现提示符(>>> 和 ...)来区分输入与输出。复现示例时,有提示符的行应输入提示符之后的全部内容;没有提示符的行是解释器的输出。示例中,如果某一行只有续行提示符而没有其他内容,就表示你需要输入一个空行,用它结束多行命令。
在官方教程页面,悬停或轻触代码示例后,可以使用右上角的“Copy”按钮。它会去掉提示符和输出,只复制输入行,方便粘贴到解释器中。
本教程的许多示例包含注释,交互式提示符下的示例也不例外。Python 注释以井号 # 开始,延续到当前物理行的末尾。注释可以位于行首,也可以跟在空白或代码后面,但不能位于字符串字面量内部。字符串字面量中的井号只是一个普通字符。注释用于解释代码,Python 不会执行它们,因此手工输入示例时可以省略注释。
例如:
# 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."
把 Python 当作计算器
先试几条简单的 Python 命令。启动解释器,等待主提示符 >>> 出现,通常很快就能看到。
数字
解释器可以充当简单的计算器:输入一个表达式,它就会输出表达式的值。表达式的语法很直观:+、-、* 和 / 可以进行算术运算,括号 () 可以分组。例如:
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5 # division always returns a floating-point number
1.6
整数,例如 2、4 和 20,属于 int 类型;带小数部分的数,例如 5.0 和 1.6,属于 float 类型。后续教程会进一步介绍数值类型。
除法 / 总会返回浮点数。若要进行向下取整除法,可以使用 // 运算符;计算余数则使用 %:
>>> 17 / 3 # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3 # floor division discards the fractional part
5
>>> 17 % 3 # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2 # floored quotient * divisor + remainder
17
Python 可以用 ** 运算符计算幂。〔** 的优先级高于 -,因此 -3**2 会被解释为 -(3**2),结果是 -9。要得到 9,可以写成 (-3)**2。〕
>>> 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
Python 完整支持浮点数。运算符的操作数类型不同时,会把整数操作数转换为浮点数:
>>> 4 * 3.75 - 1
14.0
在交互模式下,最近一次显示的表达式结果会赋给变量 _。因此,把 Python 当作桌面计算器时,可以更方便地继续计算:
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
应把这个变量当作只读变量使用,不要显式给它赋值,否则会创建一个同名的独立局部变量,遮蔽具有这种特殊行为的内置变量。
除了 int 和 float,Python 还支持其他数值类型,例如 Decimal 和 Fraction。Python 也内置支持复数,用后缀 j 或 J 表示虚部,例如 3+5j。
文本
除了数字,Python 也能处理文本。文本用 str 类型表示,通常称为“字符串”,包括字符 !、单词 rabbit、名字 Paris、句子 Got your back.,以及 Yay! :) 等。文本可以放在单引号 '...' 或双引号 "..." 中,两种方式得到的结果相同。〔与某些其他语言不同,\n 等特殊字符在单引号和双引号中具有相同含义。两者的区别是:在单引号字符串中,无需转义 ",但必须转义 ';在双引号字符串中则相反。〕
>>> 'spam eggs' # single quotes
'spam eggs'
>>> "Paris rabbit got your back :)! Yay!" # double quotes
'Paris rabbit got your back :)! Yay!'
>>> '1975' # digits and numerals enclosed in quotes are also strings
'1975'
要在字符串中包含引号,可以在它前面加上 \ 进行“转义”,也可以改用另一种引号包围字符串:
>>> 'doesn\'t' # use \' to escape the single quote...
"doesn't"
>>> "doesn't" # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
在 Python 交互式解释器中,字符串的定义形式与显示结果可能不同。print() 函数会去掉外围引号,并按实际含义输出转义字符和特殊字符,使输出更易读:
>>> s = 'First line.\nSecond line.' # \n means newline
>>> s # without print(), special characters are included in the string
'First line.\nSecond line.'
>>> print(s) # with print(), special characters are interpreted, so \n produces new line
First line.
Second line.
如果不希望 \ 后面的字符被解释为特殊字符,可以在起始引号前加上 r,使用原始字符串:
>>> print('C:\this\name') # here \t means tab, \n means newline
C: his
ame
>>> print(r'C:\this\name') # note the r before the quote
C:\this\name
原始字符串有一个细节:结尾不能有奇数个 \ 字符。相关说明和处理方式见官方 FAQ。
字符串字面量可以跨越多行。一种方式是使用三引号:"""...""" 或 '''...'''。行末的换行字符会自动包含在字符串中,但可以在相应行末加上 \,阻止它进入字符串。下面的示例没有包含开头的换行:
>>> 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'
需要拆分较长的字符串时,这个功能尤其方便:
>>> text = ('Put several strings within parentheses '
... 'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
这种方式只适用于字面量,不能直接用于变量或表达式:
>>> prefix = 'Py'
>>> prefix 'thon' # can't concatenate a variable and a string literal
File "<stdin>", line 1
prefix 'thon'
^^^^^^
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
File "<stdin>", line 1
('un' * 3) 'ium'
^^^^^
SyntaxError: invalid syntax
要拼接变量,或拼接变量与字面量,应使用 +:
>>> prefix + 'thon'
'Python'
字符串可以通过索引取得字符,第一个字符的索引为 0。Python 没有单独的字符类型;一个字符就是长度为一的字符串:
>>> 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'
注意,-0 与 0 相同,所以负索引从 -1 开始。
除了索引,字符串也支持切片。索引用于取得单个字符,而切片可以取得子字符串:
>>> 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] # 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'
切片总是包含起始位置,但不包含结束位置。这样,s[:i] + s[i:] 总是等于 s:
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
可以把索引理解为指向字符之间的边界,这有助于记忆切片的行为。第一个字符左边的边界编号为 0;长度为 n 的字符串,其最后一个字符右边的边界编号为 n。例如:
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
第一行数字给出字符串中 0 到 6 的索引边界;第二行是相应的负索引。从 i 到 j 的切片,就是边界 i 和边界 j 之间的全部字符。
如果两个非负索引都在范围内,切片的长度就是它们的差。例如,word[1:3] 的长度为 2。
使用过大的索引会报错:
>>> 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'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
如果需要不同的字符串,应创建一个新字符串:
>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'
内置函数 len() 返回字符串长度:
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
进一步阅读:
- 文本序列类型
str:字符串是序列类型,支持这类类型共有的操作。 - 字符串方法:字符串提供许多用于基本转换和搜索的方法。
- f 字符串:可以嵌入表达式的字符串字面量。
- 格式字符串语法:介绍
str.format()使用的格式。 - printf 风格的字符串格式化:详细介绍字符串作为
%运算符左操作数时使用的旧式格式化操作。
列表
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 + [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]
也可以用 list.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]
Python 中的简单赋值不会复制数据。把一个列表赋给变量时,变量引用的是已有列表。通过一个变量修改列表后,其他所有引用同一列表的变量都会看到这些变化:
>>> rgb = ["Red", "Green", "Blue"]
>>> rgba = rgb
>>> id(rgb) == id(rgba) # they reference the same object
True
>>> rgba.append("Alph")
>>> rgb
["Red", "Green", "Blue", "Alph"]
所有切片操作都会返回一个新列表,其中包含请求的元素。因此,下面的切片返回列表的浅拷贝:
>>> correct_rgba = rgba[:]
>>> correct_rgba[-1] = "Alpha"
>>> correct_rgba
["Red", "Green", "Blue", "Alpha"]
>>> rgba
["Red", "Green", "Blue", "Alph"]
也可以给切片赋值;这样甚至能够改变列表的长度,或者清空整个列表:
>>> 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
[]
内置函数 len() 也适用于列表:
>>> 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'
迈出编程的第一步
Python 能做的事情当然不只是计算二加二。例如,可以用下面的代码输出斐波那契数列开头的一段:
>>> # Fibonacci series:
>>> # the sum of two elements defines the next
>>> a, b = 0, 1
>>> while a < 10:
... print(a)
... a, b = b, a+b
...
0
1
1
2
3
5
8
这个示例引入了几个新特性:
- 第一条赋值语句使用多重赋值,变量
a和b分别获得新值0和1。循环的最后一行再次使用了多重赋值:在进行任何赋值之前,右侧的所有表达式会先完成求值;求值顺序从左到右。 - 只要条件为真,
while循环就会继续执行,这里的条件是a < 10。与 C 类似,Python 中非零整数为真,零为假。条件也可以是字符串、列表,实际上可以是任何序列:非空序列为真,空序列为假。示例中的条件是一个简单比较。标准比较运算符的写法与 C 相同:<表示小于,>表示大于,==表示等于,<=表示小于或等于,>=表示大于或等于,!=表示不等于。 - 循环体使用缩进,Python 通过缩进对语句分组。在交互式提示符下,需要为每条缩进行输入制表符或空格。实际编写较复杂的代码时,通常会使用文本编辑器;常用编辑器都具有自动缩进功能。在交互模式中输入复合语句后,需要输入一个空行来表示结束,因为语法分析器无法判断哪一行是最后一行。同一个基本块中的各行必须保持相同的缩进量。
print()函数会输出传入的参数值。它在处理多个参数、浮点数和字符串时,与前面计算器示例中直接输入表达式的行为不同。字符串输出时不带引号,各项之间会加入空格,因此可以方便地组织输出格式:
>>> i = 256*256
>>> print('The value of i is', i)
The value of i is 65536
关键字参数 end 可以避免输出末尾的换行,也可以指定用其他字符串结束输出:
>>> a, b = 0, 1
>>> while a < 1000:
... print(a, end=',')
... a, b = b, a+b
...
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
来源:Python Software Foundation 与文档贡献者,An Informal Introduction to Python。另见官方中文教程。
Copyright © 2001 Python Software Foundation; All Rights Reserved.
文档采用 Python Software Foundation License Version 2。文档中的示例、配方和代码还可按 Zero-Clause BSD License 使用。内容变更:正文转换为中文并调整文章标题与文档链接;示例代码、注释及原文示例输出保持原样;官网“Copy”按钮的说明明确指向官方教程页面。下列许可文本予以保留。
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
This LICENSE AGREEMENT is between the Python Software Foundation (“PSF”), and the Individual or Organization (“Licensee”) accessing and otherwise using this software (“Python”) in source or binary form and its associated documentation.
Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF’s License Agreement and PSF’s notice of copyright, i.e., “Copyright © 2001 Python Software Foundation; All Rights Reserved” are retained in Python alone or in any derivative version prepared by Licensee.
In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python.
PSF is making Python available to Licensee on an “AS IS” basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
This License Agreement will automatically terminate upon a material breach of its terms and conditions.
Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between PSF and Licensee. This License Agreement does not grant permission to use PSF trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party.
By copying, installing or otherwise using Python, Licensee agrees to be bound by the terms and conditions of this License Agreement.
ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.











暂无评论内容