本笔记由Markdown编辑器编辑而成。
Python简介:
Python是一种简单易学,功能强大的编程语言,它有高效率的高层数据结构,简单而有效地实现面向对象编程。Python简洁的语法和对动态输入的支持,再加上解释性语言的本质,使得它在大多数平台上的许多领域都是一个理想的脚本语言,特别适用于快速的应用程序开发。
用它来编程是非常快乐的事。
在开源哲学“早发布,常发布”的精神鼓舞下,这本书也不断发布,不断更新。
Python的特点:
(1)简单——Python的这种伪代码本质是它最大的优点之一。它使你能够专注于解决问题而不是去搞明白语言本身。
(2)易学
(3)免费,开源
(4)高层语言
——无需考虑诸如如何管理你的程序使用的内存一类的底层细节。
(5)可移植性
(6)解释性
一个用编译性语言比如C或C++写的程序可以从源文件转换到一个计算机使用的语言(二进制代码)。这个过程通过编译器和不同的标记、选项完成。
——Python语言写的程序不需要编译成二进制代码,可以直接从源代码运行程序。在计算机内部,Python解释器把源代码转换成为字节码的中间形式,然后再把它翻译成计算机使用的机器语言并运行。
(7)面向对象
(8)可扩展性
——如果你需要你的一段关键代码运行得更快或者希望某些算法不公开,你可以把这些程序用C或C++编写,然后在Python程序中使用它们。
(9)可嵌入性
可以把Python嵌入你的C/C++程序,从而向你的程序用户提供脚本功能。
(10)丰富的库
正则表达式、文档生成、单元测试、线程、数据库、网页浏览器、CGI、FTP、电子邮件、XML、HTML、WAV文件、密码系统、GUI、Tk和其他与系统有关的操作。
除了这些标准库,还有如wxPython、Twisted和Python图像库等等。
Python的基础知识
Python将一切在程序中用到的东西都作为对象。Python是完全面向对象的,在某种意义上,任何东西都被作为对象,包括数字、字符串和函数。
逻辑行和物理行——Python假定每个物理行对应一个逻辑行。
在Python中空白非常重要。在行首的主要的空白(空格键和制表符)用来决定逻辑行缩进的层次,从而来决定语句分组。
在Python中有三种控制流语句——if、for和while。
举例子代码:
if: if…elif…else
while: while…case
for: for…in….else
——else部分是可选的。如果包含else,它总是在for循环结束后执行一次,除非遇到break语句。
C++: for(int i=0; i<5; i++)
Python: for i in range(0,5)
相关的break和continue
Python中的函数
函数是重用的程序段。它们允许你给一个语句块一个名称,然后你用这个名字可以在你的程序的任何地方,任意多次地运行这个语句块。
默认参数——只有在形参表末尾的那些参数可以有默认参数值,即你不能在声明函数形参的时候,先声明有默认值的形参而后声明没有默认值的形参。因为赋给形参的值是根据位置而赋值的。
关键参数——如果你的某个函数有许多参数,而你只想指定其中的一部分,那么你可以通过命名来为这些参数赋值——这被称作关键参数——我们使用名字(关键字)而不是位置来给函数指定实参。
优势:
(1)不必担心参数的顺序,使用参数变得更加简单;
(2)假设其他参数都有默认值,可以只给想要的那些参数赋值。
Python中的模块(module)
在你的程序中定义一次函数而重用代码。
如果想要在其他程序中重用很多函数,那么答案是使用模块(module)。
from…import…
模块的name
创建自己的模块
Python的一个指导原则是“直白优于含蓄”。
dir函数:使用内建的dir函数可以列出模块定义的标识符。
包:包是模块的文件夹,有一个特殊的init.py文件,用来表明这个文件夹是特殊的,因为其包含有Python模块。
Python中的数据结构
在Python的四种内建的数据结构——列表、 元组、 字典和集合。
列表: list
处理一组有序项目的数据结构。
列表中的项目应该包括在方括号中。一旦创建了一个列表,你可以添加、删除或是搜索列表中的项目。列表是可变的数据类型。
元组
元组用来将多样的对象集合到一起。元组和列表十分类似,只不过元组和字符串一样是不可变的。
字典
键-值对。
键必须是唯一的。
键值对的存储形式:
d = key1:value1,key2:value2,key3:value3
序列
列表、元组和字符串都是序列。但是序列是什么?他们为什么如此特别呢?
集合
集合是没有顺序的简单对象的聚焦。当在聚集中一个对象的存在比其顺序或者出现的次数重要时使用集合。
使用集合,可以检查是否是成员,是否是另一个集合的子集,得到两个集合的交集等等。
未完待续……