python教程之二-----一个Python的非正式介绍
2017-09-01 14:24
375 查看
在接下来的例子中,输入和输出是由提示符(>>>和...)的存在与否来判断的。重复这个示例,你必须在提示符出来以后键入所有内容;不以提示符开头的行是解释器的输出结果。请注意在一个例子中,如果在某行中出现辅助提示符即意味着你要键入一个空行,用来结束多行命令。
在这个手册中的所有例子,即使是在交互式提示符下输入的,都将包含注释。在Python中,注释以井号开始:#,一直到这一行的结束。注释可能出现在一行的开始,或者空格和代码的后面,但不在字符串里面。字符串中的井号就表示井号本身。由于注释是为了澄清代码并且不会被Python解释,它们在某些例子中可能被省略:
一些注释的例子:
3.1 使用Python来计算
让我们来尝试一些简单的命令。启动解释器,等待主提示符的出现,>>>,通常不会花费太久
3.1.1 数字
解释器充当了一个简单的计算器:你能在里面输入表达式并且它会输出值。表达式的语法是简单明了的:操作符+,-,*,/,使用起来和其他大多数语言(例如,Pascal,C)一样;括号(())用来分组。例如:
整形数字(eg.2,4,20)是int类型,拥有小数部分的(eg. 5.0,1.6)是float类型,后面我们来了解数字类型。
除(/)总是返回float类型,如果要整除并且得到一个整形的结果(舍弃任何小数部分),可以用 // 操作符;计算余数可以用 %:
在python中,可以使用**来计算幂:
等于符号(=)用来将一个值分配给变量。然后,在下一个提示符之前,没有结果会显示出来:
如果一个变量没有定义(即赋值),尝试使用会返回一个错误:
支持所有的浮点数;混合使用的操作符类型会将整形类型转换为浮点类型:
在交互模式下,最后一个打印的表达式会被分配给变量 '_'。这意味着,当你使用python作为台式计算机时,继续计算将会变得稍微容易一点,例如:
这个变量应该被用户视为只读。不要显示的给他赋值--这将创建一个同名的局部变量来屏蔽内置的变量。
除了int和float,Python还支持其他数字类型,例如Decimal和Fraction。Python同样内置支持复杂的数字,并且使用j或J后缀来表示想象的部分(eg. 3+5j)。
在交互式解释器中,输出的字符串被包含在引号中,特殊字符将会被反斜杠转义。这有时看起来可能会与输入不同(包含的引号可以变化),但2个字符串是等价的。如果字符串包含单引号并且没有双引号,整个字符串应该用单引号包含,否则应该是双引号。print()函数通过省略包含的引号和打印转义符和特殊字符来产生一个更加可读的输出:
如果你不想字符被转义,你可以使用原始字符串,在第一个引号前面加上'r':
如果字符串跨越多行,一个方法是使用3引号:"""..."""或者'''...''',这一行的结尾将会自动添加到字符串中,你可以在这一行的末尾添加一个 \ 来防止这种情况:
将产生如下输出(注意不包括初始的换行符):
字符串能用+操作符串联在一起,用*操作符重复:
2个或以上的相邻的字符串(即包含在引号中)会自动串联在一起:
这只适用于常量,而不是变量或者表达式:
如果你要串联多个变量或者一个变量和一个常量,使用+操作符:
当你想拆分比较长的字符串时,这个特性尤为有用:
字符串可以用索引(下标)表示,第一个字符的索引为0。没有单独的字符类型;一个字符就是一个大小为1的字符串:
索引值也可以为负数,表示从右开始计算:
注意因为-0和0相等,所以负数索引从-1开始
除了索引之外,还支持切片。索引用来获取单个字符,切片可以获取子字符串:
注意开始总是包括在内,而结尾总是排除在外,这就是说s[i:]+s[:i]总是等于s:
切片索引具有有用的缺省值;省略的第一个索引默认为0,省略的第二个索引默认为被切片字符串的大小。
一种记住切片原理的方法是将切片看作字符间的指针,左边第一个字符为0,右边包括n个字符的字符串索引为n,例如:
第一排数字给出了字符串中0-6的切片位置,第二排数字给出了相应的反方向的切片。从i到j的切片包含标记为i和j位置之间的所有字符
对于非负切片,如果都在边界内,那么切片的长度就是2个索引之间的差值。例如:word[1:3]的长度是2
尝试使用一个太大的索引将会导致一个错误:
然而,在使用切片时,越界的切片索引将能很好的处理:
Python字符串的值不能被改变----它们是不可变的。因此,在字符串中给一个索引位置赋值将会导致一个错误:
如果你需要一个不同的字符串,你应该创建一个新的:
内置函数len()返回一个字符串的长度:
和字符串(以及其他内建的序列类型)一样,列表能被索引和切片:
所有的切片操作返回一个包含请求元素的新的列表。这就意味着下述切片返回一个新的(浅备份)列表副本:
列表同样支持串联操作:
和不可变的字符串不同,列表是可变类型。也就是说,可以改变他们的内容:
你也可以在列表的末尾添加新的项目,使用append()方法来完成这个操作:
对切片赋值也是可以的,这甚至可以改变列表的大小或者完全清除它:
内置函数len()同样适用于列表:
也可以嵌套列表,例如:
这个例子包含几个新的特征。
第一行包含一个多重赋值。变量a和变量b同时得到了新值0和1。在最后一行中,这个特性再次被用到,这表明在任何赋值动作发生之前,右手边的表达式将会首先被求值。右手边的表达式是从左到右求值的。
只要条件(这里是:b < 10)为真,while循环就会一直执行,就像C中的,任何非0的整形值都是True;0是false。条件也可以是一个字符串或者一个列表值,事实上,任何序列都可以;任何非0长度都是true,空序列是false。本例使用的是一个比较简单的比较。标准比较操作符和C中一致:<(小于),>(大于),==(等于),<=(小于等于),>=(大于等于),!=(不等于)
循环的主体是缩进的:缩进是Python语法的一种分组方式。在交互式提示符后面,你必须输入一个制表符或者多个空格来表示缩进。实际中你将使用文本编辑器准备更多复杂的输入;所有优秀的文本编辑器都有自动缩进功能。当一个组合式语句被交互式的输入时,必须有一个空行来表示输入完成(因为解析器无法得知你什么时候输入的是最后一行)。注意在同一个块中,所有的行必须有同样的缩进。
print()函数将写出它所给的参数的值。它不同于写入你想要写的表达式(正如我们在上面的计算例子中一样)来处理多个参数,浮点数,字符串一样。字符串以没有引号的方式被打印,并且在项目之间插入了空格。所以你可以漂亮的格式化你的东西,如:
在这个手册中的所有例子,即使是在交互式提示符下输入的,都将包含注释。在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来计算
让我们来尝试一些简单的命令。启动解释器,等待主提示符的出现,>>>,通常不会花费太久
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
整形数字(eg.2,4,20)是int类型,拥有小数部分的(eg. 5.0,1.6)是float类型,后面我们来了解数字类型。
除(/)总是返回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
在python中,可以使用**来计算幂:
>>> 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后缀来表示想象的部分(eg. 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.'
在交互式解释器中,输出的字符串被包含在引号中,特殊字符将会被反斜杠转义。这有时看起来可能会与输入不同(包含的引号可以变化),但2个字符串是等价的。如果字符串包含单引号并且没有双引号,整个字符串应该用单引号包含,否则应该是双引号。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
如果字符串跨越多行,一个方法是使用3引号:"""..."""或者'''...''',这一行的结尾将会自动添加到字符串中,你可以在这一行的末尾添加一个 \ 来防止这种情况:
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'
2个或以上的相邻的字符串(即包含在引号中)会自动串联在一起:
>>> '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.'
字符串可以用索引(下标)表示,第一个字符的索引为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开始
除了索引之外,还支持切片。索引用来获取单个字符,切片可以获取子字符串:
>>> 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'
切片索引具有有用的缺省值;省略的第一个索引默认为0,省略的第二个索引默认为被切片字符串的大小。
>>> 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位置之间的所有字符
对于非负切片,如果都在边界内,那么切片的长度就是2个索引之间的差值。例如: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' ... 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
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 []
内置函数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 b < 10: ... print(b) ... a, b = b, a+b ... 1 1 2 3 5 8
这个例子包含几个新的特征。
第一行包含一个多重赋值。变量a和变量b同时得到了新值0和1。在最后一行中,这个特性再次被用到,这表明在任何赋值动作发生之前,右手边的表达式将会首先被求值。右手边的表达式是从左到右求值的。
只要条件(这里是:b < 10)为真,while循环就会一直执行,就像C中的,任何非0的整形值都是True;0是false。条件也可以是一个字符串或者一个列表值,事实上,任何序列都可以;任何非0长度都是true,空序列是false。本例使用的是一个比较简单的比较。标准比较操作符和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 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,
相关文章推荐
- Python Tutorial(三):一个对Python的非正式介绍
- python学习教程(十二),一个文本界面下网络聊天室
- C/C++ socket编程教程之二:一个简单的Linux下的socket程序
- 分享一个python cookbook的在线教程地址
- Scott Mitchell 的ASP.NET 2.0数据教程之二:创建一个业务逻辑层
- 【廖雪峰 python教程 课后题 切片】利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法:
- 简明Python教程之编写一个Pyhton脚本
- Python基础教程,用jupyter notebook建立一个新的Python工程
- python基础教程之基本数据类型和变量声明介绍
- Scott Mitchell 的ASP.NET 2.0数据教程之二:创建一个业务逻辑层
- 用Python实现一个简单的多线程TCP服务器的教程
- ASP.NET 2.0数据教程之二:创建一个业务逻辑层
- NodeJs教程(介绍总结!)终于在网上找到一个靠谱点的了T_T
- Python学习入门基础教程(learning Python)--8.3 字典常用的方法函数介绍
- Python学习笔录(二)--- Python的非正式介绍
- Python正则表达式教程之二:捕获篇
- Python教程(0)——介绍
- python基础教程之自定义函数介绍
- 简明Python3教程 3.介绍