本手册中的许多示例(包括在交互式提示中输入的示例)都包含注释。 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类型。 本教程稍后会介绍更多关于数字类型的内容。
除法(/)总是返回一个浮点数。 要进行地板划分并获得整数结果(放弃任何小数结果),可以使用//运算符; 计算余数,你可以使用%:
>>> 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
>>> 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还可以处理字符串,可以用几种方式表示。 它们可以用单引号('...')或双引号(“...”)括起来,结果相同。 \可以用来转义引号:
>>> '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'
当您想要分隔长字符串时,此功能特别有用:
>>> 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 ... SyntaxError: invalid syntax >>> ('un' * 3) 'ium' ... SyntaxError: invalid syntax
如果要连接变量或变量和文字,请使用+:
>>> prefix + 'thon' 'Python'
字符串可以被索引(下标),第一个字符的索引为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'
除了索引之外,还支持切片。 虽然索引用于获取单个字符,但切片允许您获取子字符串:
>>> 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'
记住切片工作原理的一种方式是将索引视为指向字符,其中第一个字符的左边缘编号为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的边缘之间的所有字符组成。
对于非负数指数,如果两者都在边界内,那么切片的长度就是指数的差值。 例如,单词[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' ... 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样式的字符串格式
在字符串是%运算符的左操作数时调用的旧格式操作在这里更详细地描述。
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[:] [1, 4, 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]
您还可以使用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]
对切片的分配也是可能的,这甚至可以改变列表的大小或完全清除它:
>>> 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
[]
>>> 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 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;零是错误的。该条件也可以是一个字符串或列表值,实际上可以是任何序列;任何长度不为零的东西都是真的,空序列是错误的。本例中使用的测试是一个简单的比较。标准比较运算符的写法与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 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,原文链接: https://docs.python.org/3/tutorial/introduction.html