python教程之二-----一个Python的非正式介绍
来源:互联网 发布:淘宝页面怎么装修 编辑:程序博客网 时间:2024/05/19 09:04
在接下来的例子中,输入和输出是由提示符(>>>和...)的存在与否来判断的。重复这个示例,你必须在提示符出来以后键入所有内容;不以提示符开头的行是解释器的输出结果。请注意在一个例子中,如果在某行中出现辅助提示符即意味着你要键入一个空行,用来结束多行命令。
在这个手册中的所有例子,即使是在交互式提示符下输入的,都将包含注释。在Python中,注释以井号开始:#,一直到这一行的结束。注释可能出现在一行的开始,或者空格和代码的后面,但不在字符串里面。字符串中的井号就表示井号本身。由于注释是为了澄清代码并且不会被Python解释,它们在某些例子中可能被省略:
一些注释的例子:
# this is the first commentspam = 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 + 24>>> 50 - 5*620>>> (50 - 5*6) / 45.0>>> 8 / 5 # division always returns a floating point number1.6
整形数字(eg.2,4,20)是int类型,拥有小数部分的(eg. 5.0,1.6)是float类型,后面我们来了解数字类型。
除(/)总是返回float类型,如果要整除并且得到一个整形的结果(舍弃任何小数部分),可以用 // 操作符;计算余数可以用 %:
>>> 17 / 3 # classic division returns a float5.666666666666667>>>>>> 17 // 3 # floor division discards the fractional part5>>> 17 % 3 # the % operator returns the remainder of the division2>>> 5 * 3 + 2 # result * divisor + remainder17
在python中,可以使用**来计算幂:
>>> 5 ** 2 # 5 squared25>>> 2 ** 7 # 2 to the power of 7128
等于符号(=)用来将一个值分配给变量。然后,在下一个提示符之前,没有结果会显示出来:
>>> width = 20>>> height = 5 * 9>>> width * height900
如果一个变量没有定义(即赋值),尝试使用会返回一个错误:
>>> n # try to access an undefined variableTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'n' is not defined
支持所有的浮点数;混合使用的操作符类型会将整形类型转换为浮点类型:
>>> 4 * 3.75 - 114.0
在交互模式下,最后一个打印的表达式会被分配给变量 '_'。这意味着,当你使用python作为台式计算机时,继续计算将会变得稍微容易一点,例如:
>>> tax = 12.5 / 100>>> price = 100.50>>> price * tax12.5625>>> price + _113.0625>>> round(_, 2)113.06
这个变量应该被用户视为只读。不要显示的给他赋值--这将创建一个同名的局部变量来屏蔽内置的变量。
除了int和float,Python还支持其他数字类型,例如Decimal和Fraction。Python同样内置支持复杂的数字,并且使用j或J后缀来表示想象的部分(eg. 3+5j)。
3.1.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.'
>>> '"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 lineFirst line.Second line.
>>> print('C:\some\name') # here \n means newline!C:\someame>>> print(r'C:\some\name') # note the r before the quoteC:\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.'
>>> 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'
>>> 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'
+---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 6-6 -5 -4 -3 -2 -1
>>> word[42] # the word only has 6 charactersTraceback (most recent call last): File "<stdin>", line 1, in <module>IndexError: string index out of range
>>> word[4:42]'on'>>> word[42:]''
>>> 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'
>>> s = 'supercalifragilisticexpialidocious'>>> len(s)34
3.1.3 列表
>>> squares = [1, 4, 9, 16, 25]>>> squares[1, 4, 9, 16, 25]
>>> squares[0] # indexing returns the item1>>> 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]
>>> 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 迈向编程的第一步
>>> # Fibonacci series:... # the sum of two elements defines the next... a, b = 0, 1>>> while b < 10:... print(b)... a, b = b, a+b...112358
- 第一行包含一个多重赋值。变量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教程之二-----一个Python的非正式介绍
- [Python教程]3.一份非正式的Python教程
- Python Tutorial 第三章 Python非正式介绍
- python 2.7 中文教程-3:非正式教程
- Python 学习之二:Python超短教程
- Python基础学习教程(二)之序列的宝藏
- Python 教程介绍
- 【美妙的Python之二】Python初步
- Python教程:numpy的基本介绍
- #Python 初学之二编写一个小游戏#
- Python 教程 二
- 二、python笔记之用python做一个小游戏
- 简明Python教程的一个例子
- 【Python教程】python之路
- 【Python】分享一个大牛的Python教程
- 「学习笔记——Python」Python非正式导引
- Python 教程之零
- python web开发 之 flask教程(二)
- android app性能测试
- python基础学习五——函数
- 搜狐集团2018秋季校招笔试题 kolakoski序列
- 二分查找
- Retrofit 2.2 传递数组参数
- python教程之二-----一个Python的非正式介绍
- squirrel-foundation状态机的使用细节
- sql 优化注意事项
- 静态链接的整个过程
- GCD中任务与队列(一)
- 简单斐波那契
- 单选,反选,全选
- 负载均衡基础知识
- 从ttf原始文件解析出字体名称时遇到的字节序的问题是big endian