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. 数字¶
解释器充当一个简单的计算器:您可以在其上键入一个表达式,它将写入该值。表达式语法很简单:运算符 +
,-
,*
和 /
的工作方式与大多数其他语言(例如,Pascal或C)相似;圆括号(()
)可用于分组。例如:
>>> 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
。我们稍后将在教程中看到更多关于数值类型的内容。
除法(/
)总是返回一个浮点数。要做 floor division 并获得一个整数结果(丢弃任何分数结果),您可以使用 //
运算符;计算余数你可以使用 %
:
>>> 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 # result * 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
有完全支持浮点;具有混合类型操作数的运算符将整数操作数转换为浮点:
>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5
在交互模式下,最后打印的表达式分配给变量 _
。这意味着,当您使用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也可以操纵字符串,可以用几种方式表示。它们可以用单引号('...'
)或双引号("..."
)括起来,具有相同的结果 [2]。 \
可用于转义引号:
>>> 'spam eggs' # single quotes
'spam eggs'
>>> 'doesn\'t' # use \' to escape the single quote...
"doesn't"
>>> "doesn't" # ...or use double quotes instead
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
在交互式解释器中,输出字符串用引号括起来,特殊字符用反斜杠转义。虽然这可能看起来不同于输入(包含引号可能改变),但两个字符串是等效的。如果字符串包含单引号和双引号,则该字符串将括在双引号中,否则它将括在单引号中。 print()
函数通过省略引号和打印转义和特殊字符产生更易读的输出:
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')
"Isn't," she said.
>>> s = 'First line.\nSecond line.' # \n means newline
>>> s # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s) # with print(), \n produces a 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'
这只适用于两个字面量,而不是与变量或表达式:
>>> prefix = 'Py'
>>> prefix 'thon' # can't concatenate a variable and a string literal
...
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
...
SyntaxError: invalid syntax
如果要连接变量或变量和文字,请使用 +
:
>>> prefix + 'thon'
'Python'
当您想要断开长字符串时,此功能特别有用:
>>> text = ('Put several strings within parentheses '
... 'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
字符串可以是 indexed (下标),第一个字符的索引为0.没有单独的字符类型;一个字符只是一个大小为1的字符串:
>>> 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开始。
除了索引,还支持 slicing。虽然索引用于获取单个字符,但 slicing 允许您获取子字符串:
>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'
注意如何始终包括开始,并且始终排除结束。这确保 s[:i] + s[i:]
总是等于 s
:
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
切片索引具有有用的默认值;省略的第一个索引默认为零,省略的第二个索引默认为要分割的字符串的大小。
>>> 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'
记住切片如何工作的一种方式是将索引视为指向 between 字符,第一个字符的左边缘为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字符串不能更改—它们是 immutable。因此,分配给字符串中的索引位置会导致错误:
>>> word[0] = 'J'
...
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
...
TypeError: 'str' object does not support item assignment
如果你需要一个不同的字符串,你应该创建一个新的:
>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'
内置函数 len()
返回字符串的长度:
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
参见
- 文本序列类型— str
字符串是 序列类型 的示例,并支持这些类型支持的常见操作。
- 字符串方法
字符串支持大量的基本转换和搜索方法。
- 格式化字符串文字
具有嵌入表达式的字符串文字。
- 格式字符串语法
有关使用
str.format()
的字符串格式化的信息。- printf 样式字符串格式
当字符串和Unicode字符串是
%
运算符的左操作数时调用的旧格式化操作在这里更详细地描述。
3.1.3. 列表¶
Python知道一些 compound 数据类型,用于将其他值分组在一起。最通用的是 list,它可以写成逗号分隔的值(项目)在方括号之间的列表。列表可能包含不同类型的项目,但通常所有项目都具有相同的类型。
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
像字符串(和所有其他内置的 sequence 类型),列表可以索引和切片:
>>> squares[0] # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:] # slicing returns a new list
[9, 16, 25]
所有切片操作返回包含所请求元素的新列表。这意味着以下slice返回一个新的(浅)副本的列表:
>>> squares[:]
[1, 4, 9, 16, 25]
列表还支持连接等操作:
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
与字符串(即 immutable)不同,列表是 mutable 类型,即可以改变它们的内容:
>>> 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]
您还可以使用 append()
method 在列表末尾添加新项目(稍后我们将更多地了解方法):
>>> 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]
分配到切片也是可能的,这甚至可以更改列表的大小或完全清除:
>>> 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 系列的初始子序列:
>>> # 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
本示例介绍了几个新功能。
第一行包含一个 多重分配:变量
a
和b
同时获得新值0和1.在最后一行,这被再次使用,表明右侧的表达式在任何赋值之前都被先计算地点。右侧表达式从左到右计算。只要条件(这里:
b < 10
)保持为真,while
循环就执行。在Python中,和C一样,任何非零整数值都是true;零为假。条件也可以是字符串或列表值,实际上是任何序列;任何具有非零长度的值都为true,空序列为false。在该示例中使用的测试是简单的比较。标准比较运算符的写法与C:<
(小于),>
(大于),==
(等于),<=
(小于或等于),>=
(大于或等于)和!=
不等于)。循环的 body 是 indented:缩进是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 b < 1000: ... print(b, end=',') ... a, b = b, a+b ... 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
脚注
[1] | 由于 |
[2] | 与其他语言不同, |