3. Python 非正式介绍¶
在以下示例中,输入和输出通过是否存在提示符(>>> 和 …)来区分:要重复该示例,当提示符出现时,您必须键入提示符之后的所有内容;不以提示符开头的行是解释器的输出。请注意,示例中单独一行的次级提示符意味着您必须键入一个空行;这用于结束多行命令。
您可以使用“复制”按钮(当鼠标悬停或点击代码示例时,它会出现在右上角),该按钮会去除提示符并省略输出,以便将输入行复制并粘贴到您的解释器中。
本手册中的许多示例,即使是在交互式提示符下输入的示例,也包含注释。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."
3.1. 将 Python 用作计算器¶
让我们尝试一些简单的 Python 命令。启动解释器并等待主提示符 >>>
。(这应该不会花很长时间。)
3.1.1. 数字¶
解释器充当一个简单的计算器:您可以向它键入表达式,它将写入值。表达式语法很简单:运算符 +
、-
、*
和 /
可用于执行算术运算;括号 (()
) 可用于分组。例如
>>> 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 中,可以使用 **
运算符来计算幂 [1]
>>> 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
完全支持浮点数;混合类型操作数的运算符会将整数操作数转换为浮点数
>>> 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
)。
3.1.2. 文本¶
Python 可以处理文本(由类型 str
> 表示,即“字符串”)以及数字。这包括字符“!
”、单词“rabbit
”、名称“Paris
”、句子“Got your back.
”等。“Yay! :)
”。它们可以用单引号 ('...'
) 或双引号 ("..."
) 括起来,结果相同 [2]。
>>> '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 shell 中,字符串定义和输出字符串看起来可能有所不同。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:\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'
当你想断开长字符串时,这个特性特别有用
>>> 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。没有单独的字符类型;字符只是大小为一的字符串
>>> 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 风格的字符串格式化
当字符串是
%
运算符的左操作数时调用的旧格式化操作在此处有更详细的描述。
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 + [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'
3.2. 编程的初步步骤¶
当然,我们可以使用 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
)保持为真就会一直执行。在 Python 中,与 C 语言一样,任何非零整数值都为真;零为假。条件也可以是字符串或列表值,实际上可以是任何序列;任何非零长度的都为真,空序列为假。示例中使用的测试是一个简单的比较。标准比较运算符与 C 语言相同:<
(小于)、>
(大于)、==
(等于)、<=
(小于或等于)、>=
(大于或等于)和!=
(不等于)。循环的 主体 是 缩进 的:缩进是 Python 语句分组的方式。在交互式提示符下,对于每个缩进行,你必须键入一个制表符或空格。实际上,你将使用文本编辑器为 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,
脚注