VII Python(1)基础知识

1989年诞生(同LinuxOS),google推崇,06年后才开始在中国流行,08年运维开始使用python

www.python.org(主流OS默认配的python为2.6或2.7,最好在Ubuntu12.10上使用python,对于开发很方便,否则会浪费很多时间在装某一软件包)

https://www.python.org/ftp/python/

Python(简单、容易上手、语法非常简明,任何功能都可实现;胶水语言,粘合剂,能与任何语言结合起来(如java、php、perl等)互相调用)

Python3.3(加入新功能,仅简单语法有变化整体90%以上同2.7和2.6,3.3是2.7的过渡能识别2.7的语法及功能)

Win上(pythonXY、portable python可放在U盘到哪都能用)

模块(为实现对程序特定功能的调用和存储,可将代码封装起来供其它程序调用),可以交互使用的一个代码段,或来自一个大规模的python程序,一旦导入一个模块就可引用它的任何的公共函数、类或属性(格式:>>>MODULE.FUNCTION,例如>>>sys.path)

使用模块的好处(程序可扩展性、减少程序代码、方便程序架构的更改)

注:python自带有200多个模块,官网已收集2000多个模块,基本可找到想要的任何功能

注:并非所有模块都保存为*.py文件,如内置模块sys源代码是用C写的不是python所以不是.py文件,sys是置于python内部的

注:perl古老的语言,在文字处理方面(正则)非常强大,语法复杂,不适合团队开发;

注:php,轻量级的web开发,php能实现的python都能实现,php在C/S架构方面并不擅长,而pythonserver方面非常强悍,在web方面python一点不比php差;

注:软件工程师(编程,软件开发,游戏、搜索、嵌入式、网站、C/S软件),系统工程师(用python管理系统,脚本、运维自动化工具);

注:shell和python,shell重在脚本方面,而python是语言,面向对象的语言,不止脚本方面

注:软件开发过程(分析(什么)-->设计(如何)-->实施(编写)-->测试与调试(测试)-->实施或开发(使用)-->优化(维护);面向对象的编程(把数据和功能结合起来,用对象将其包起来组织程序的方法);面向过程的编程(根据操作数据的函数或语句块来设计程序);当要开发大程序或寻求更合适解决方案的时候使用面向对象的编程技术

注:puppet(ruby)与python的外部框架类似

在python中一切皆对象,字符串是对象,列表是对象,函数是对象,模块是对象,一切都可以赋值给变量或作为参数传递给函数,所有函数都有一个内置的__doc__属性,它会返回在函数源代码中定义的doc string,sys模块是一个对象,它有一个叫作path的属性等

代码块指:函数、if语句、for循环、while循环等等,代码块通过缩进来定义,缩进是python这种语言的要求而并非是一种风格

测试模块:if__name==”__main__”:(注:if语句表达式不需用括号()括起来,以冒号结束,随后是缩进)

在python中向屏幕输出内容只用print即可,print语句可接受任何数据类型(字符串、整数、字典、列表等),甚至多种数据类型可混在一起输出到一行(各数据类型间用逗号分隔),显示在屏幕上时是用空格隔开的,逗号并不打印

Python中使用硬回车分割语句,冒号和缩进分割代码块;C++和JAVA使用分号分割语句,花括号来分割代码块

模块是对象,所有模块都有一个内置属性__name__,一个模块的__name__的值要看具体如何应用模块,如果import模块,那__name__的值通常为模块的文件名(无路径和文件扩展名),如果像标准程序一样直接运行模块那__name__的值是一个特别的默认值__main__,了解到这一点,你可在模块内部为你的模块设计一个测试套件(加入if语句),当运行模块时__name__的值是__main__测试套件执行,当导入模块时__name__的值就是特别的东西了,测试套件被忽略,这样使得将新的模块集成到一个大程序之前开发和调试容易多了

[root@localhost ~]# uname -a

Linux localhost.localdomain 2.6.32-358.el6.x86_64#1 SMP Tue Jan 29 11:47:41 EST 2013 x86_64 x86_64 x86_64 GNU/Linux

[root@localhost ~]# python -V

Python 2.6.6

[root@localhost ~]# which python

/usr/bin/python

[root@localhost ~]# vim test.py

----------script start---------------

#!/usr/bin/env python

#

def buildConnectionString(params):

"""Build a connection string from a dictionary ofparameters.

Returnsstring."""

return ";".join(["%s=%s" % (k, v) for k, v inparams.items()])

if __name__ == "__main__":

myParams = {"server":"mpilgrim", \

"database":"master", \

"uid":"sa",\

"pwd":"secret"\

}

printbuildConnectionString(myParams)

---------------script end--------------

注:脚本第一行#!/usr/bin/python称为组织行;第二行注释信息,重要,有助于理解代码的意义;三引号中的内容是函数的docstrings注释信息;def、if、while、for、print这些是操作符,print后引号中的内容是字符串;return定义函数返回值,一个函数中只能有一个return语句,return可理解为返回并退出

[root@localhost ~]# python test.py(使用python SCRIPT_NAME,即可运行python脚本)

pwd=secret;database=master;uid=sa;server=mpilgrim

[root@localhost ~]# python(进入python编辑器模式)

Python 2.6.6(r266:84292, Oct 12 2012, 14:23:48)

[GCC 4.4.6 20120305 (Red Hat 4.4.6-4)]on linux2

Type "help","copyright", "credits" or "license" for moreinformation.

>>> print 'hello world'

hello world

[root@localhost ~]# yum -y installzlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-develtk-devel

[root@localhost ~]# tar xf Python-2.7.3.tgz

[root@localhost ~]# cd Python-2.7.3

[root@localhost Python-2.7.3]#./configure --prefix=/usr/local/python2.7/

[root@localhost Python-2.7.3]#make && make install

[root@localhost Python-2.7.3]#cd

[root@localhost ~]# ln -s /usr/local/python2.7/bin/python2.7 /usr/bin/python2.7

[root@localhost ~]# python2.7 -V

Python 2.7.3

[root@localhost ~]# python2.7

Python 2.7.3(default, May  2 2016, 06:57:54)

[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)]on linux2

Type "help","copyright", "credits" or "license" for moreinformation.

>>> import sys,os

[root@localhost ~]# whereis python

python: /usr/bin/python2.7/usr/bin/python2.6 /usr/bin/python /usr/bin/python2.6-config /usr/lib/python2.6/usr/lib64/python2.6 /usr/include/python2.6 /usr/local/python2.7/usr/share/man/man1/python.1.gz

一、

Python编程风格:

1、语法要求:

缩进统一(shell中的循环语句有关闭符号(fi、done),而python中无关闭符号,用缩进替代,敲两下回车即输入结束,程序从第二行开始之后的内容要统一格式,要么一个或两个或四个空格(TAB键默认4个空格),否则语法错误(incident error));

注:缩进在python中是语法要求而不是风格

变量(变量名由字母、数字、下划线组成,且第一个字符不能是数字(变量名的第一个字符必须是大写字母或小写字母或下划线(_);变量名的其它部分可由大小写字母或下划线或数字组成);变量名对大小写敏感,如myname和myName是不同的变量)

注:python与大多数语言一样,有局部变量和全局变量之分,但无明显的变量声明,变量通过首次赋值产生,当超出作用范围时自动消亡

注:当一条命令用续行符\分割成多行时,后续的行可以以任何方式缩进,在()、[]、{}中的表达式可用也可不用换行符,若使用换行符可使代码读起来更容易,这只是风格而已

注:python不允许引用一个未被赋值的变量,否则会引发异常,赋值时可一次赋多值,也可连续值赋值,具体看以下举例

格式化字符串(用%s)、格式化整数(用%d)、格式化浮点数(用%f),字符串格式化不仅是格式化,还是连接,也是强制类型转换

字符串连接用“+”符号

>>> help(str)  #显示str类的帮助,str类保存程序使用的各种文本(字符串)

常量(字面意义上的称为常量,如:’it’s a string’、5)

数(python中有四种类型的数:整数、长整数(超过1位数的整数)、浮点数(如52.3E-4表示52.3*10-4、复数(如-5+4j或2.3-4.6j))

字符串(字符的序列,’string’,”string”,单引号中的字符串与双引号中的字符串完全相同;三引号中可引用多行字符串,在三引号中可自由的使用单双引号;转义符\,如’what\’syour name’若不加转义符python会不明白字符串从何处开始,同理使用双引号时也要加转义符;\\表示\本身;行末的\表示续行,字符串在下一行继续(未完待续);自然字符串用r或R,如r”newllines are indicated by\n”,r或R都可,引号中的所有内容按原样输出

注:在小括号()、中括号[]、大括号{}内可不使用转义符\,称为暗示的行连接

注:一定要用自然字符串处理正则表达式,否则会需要使用很多反斜杠\,如向后引用符’\\1’赞同于r’\1’

变量(可用于存储任何东西,变量命名规则(标识符的命名):字母、数字、下划线组成且第一个字符不能是数字;变量名大小写敏感)

数据类型(变量可处理不同类型的值称数据类型)

对象(python在程序中用到的任何东西都为对象,数、函数、字符串、模块等都是对象;所有python程序都以扩展名.py结尾;python中使用变量直接赋值,不需事先声明或定义数据类型)

逻辑行与物理行(逻辑行是python所看见的单个语句,物理行是编写程序时肉眼所看见的所见即所得,行末可用分号表示一个逻辑行语句的结束;建议在一个物理行写一句逻辑行,当逻辑行太长时用多个物理行写一个逻辑行(注意若不在括号内要使用续行符\),尽可能避免不使用分号,从而让代码更加易读)

注:

I=5

Print I等同于

I=5;

Print I等同于

I=5;print I;等同于

I=5;print I

缩进(同一层次的语句(一个代码块)必须要有相同的缩进,建议使用<TAB>默认四个空格,若空格和<TAB>混用程序移植后可能会出问题)

运算符与表达式(逻辑行中都包含表达式,一个表达式可理解为运算符和操作数,如2+3,2和3是操作数,+是运算符;运算符功能:完成某件事,需要数据来进行运算;+-*/,按位与&,按位或|,按位异或^,按位翻转~,<<左移,>>右移,**幂(如3**4表示34),//取整除(4//3.0得1.0返回商的整数部分),%模(8%3得2返回除法的余数),<,>,<=,>=,not布尔“非”,and布尔“与”;in,notin用于成员测试,is,isnot用于同一性测试)

举例:

有效变量名(i、_my_name、name_23、a1b2_c3)

无效变量名(2things、this is spaced out、my-name)

>>> name='jowin'

>>> print name

jowin

>>> if name=='jowin':(注意此句结尾是冒号)

...    print 'hello',name(此处敲两下回车即输入结束)

...

hello jowin

(一次赋多值,此例v是一个三元素的tuple,(x,y,z)是一个三变量的tuple,将一个tuple赋值给另一个tuple,会按照先后顺序对应的赋给每个变量)

>>>v=("a","b","e")

>>> v

('a', 'b', 'e')

>>> (x,y,z)=v

>>> x

'a'

>>> y

'b'

>>> z

'e'

(连续值赋值,内置的range函数返回连续的整数list,range的简化使用如range(7)接收一个上限值,返回一个初始值从0开始的list,依次递增但不包含上限值)

>>> range(7)

[0, 1, 2, 3, 4, 5, 6]

>>> range(1,8)

[1, 2, 3, 4, 5, 6, 7]

>>>(MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY)=range(1,8)

>>> MONDAY

1

>>> SATURDAY

6

(整个表达式的计算结果为一个字符串,第一个%s被变量k的值替换,第二个%s被变量v的值替换,其它字符原样输出,(k,v)是一个tuple

>>> k="uid"

>>> v="sa"

>>> "%s=%s" % (k,v)

'uid=sa'

字符串格式化与字符串连接比较

>>> uid="sa"

>>> pwd="secret"

>>> print pwd+"is not a goodpassword for"+uid

secretis not a good password forsa

>>> print "%s is not a goodpassword for %s" % (pwd,uid)  (此处字符串连接与字符串格式化结果一样)

secret is not a good password for sa

注:(userCount,)是一个只包含一个元素的tuple,显示的说明这是一个tuple而不是其它,当定义一个list、dictionary、tuple可以总是在最后一个元素后面跟上逗号,但要定义仅包含一个元素的tuple时逗号是必须的否则python不知道(userCount,)是包含一个元素的tuple还是变量userCount的值

>>> userCount=6

>>> print "Usersconnected:%d" % (userCount,)

Users connected:6

>>> print "Usersconnected:"+userCount   (将字符串与非字符串连接会产生异常)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: cannot concatenate 'str' and'int' objects

格式化浮点数,%f十进制浮点数,不指定精度时默认打印6位小数

>>> print "today's stockprice:%f" % 50.4625

today's stock price:50.462500

>>> print "today's stockprice:%.2f" %50.4625

today's stock price:50.46

>>> print "today's stockprice:%+.2f" %50.4625

today's stock price:+50.46

2、单引号(强引用)、双引号(弱引用)、三引号(’’’或”””用于注释,可多行)

注:三引号用于注释(docstring),三引号的内容可包含多行字符串,在开始与结束间的所有东西都被视为单个字符串的一部分(包括硬回车和引号);三引号(doc string)可用于提供上下文敏感文档信息,如键入一个函数名时,将显示提示信息,这会非常有用

注:在脚本中若注释一行在行首使用#,注释多行在开始和结尾处使用’’’或”””

3、在编辑模式下,可直接用于计算

>>> 3 * 2 / 2(可在编辑模式下直接做算述运算,在shell下是用bc)

3

>>> 88*2/2

88

>>> a=8

>>> b=6

>>> a>b

True

>>> a<b

False

>>> a!=b

True

4、赋值(用等号=赋值,用双等号==作判断)

>>> User_name='jowin'

>>> print User_name

jowin

>>> Age=27

>>> print Age

27

>>> Next_year_age=Age+1

>>> print Next_year_age

28

>>> name=chai(此句是把chai当作变量,变量chai之前没有赋过值,所以报错未定义)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'chai' is not defined

>>> chai='hehe'

>>> print chai

hehe

>>> print name

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'name' is not defined

>>> name=chai

>>> print name

hehe

5、函数是在程序中将一组用特定的格式包装起来,定义一个名称,然后可在程序的任何地方通过调用此函数名来执行函数里的那组命令;

使用函数的好处:程序可扩展性;减少程序代码,方便程序架构的更改

函数声明以关键字def开始,后接函数名,()内为参数,多个参数用逗号分隔(param1,param2);

函数没有定义返回的数据类型,python不需要指定返回值的数据类型和返回值,每个python函数都有返回值,若函数执行过return语句则将返回指定的值,否则返回None(python的空值);

Python中函数的参数不需指定数据类型,python会判断一个变量是什么类型,并在内部将其记录下来;

函数有默认参数、关键参数、局部变量、全局变量、return、docstrings

函数形参、实参(函数中的参数称为形参,提供给函数调用的值称为实参)

函数取得的参数是你提供给函数的值,函数就可利用这些值来做事,这些参数犹如变量一样,只不过它们的值是在我们调用函数时定义的,而非在函数本身内赋值

局部变量(当在函数内定义变量时,定义的变量与函数外具有相同名称的其它变量没任何关系,即变量名称对函数来说是局部的(称变量的作用域),所有变量的作用域是它们被定义的块)

全局变量(用global声明变量是全局的,未声明为global的变量是不能为定义在函数外的变量赋值的,不建议使用global否则不容易搞清楚变量是在哪定义的)

函数默认参数值(在函数的形参后用赋值运算符=给形参指定默认值;注意只有在形参末尾的那些参数可有默认值,如def func(a,b=5)这是有效的,而def func(a=5,b)这是无效的;默认参数值应该是一个参数,更加准确的讲默认参数值应该是不可变的)

函数关键参数(若函数中有许多参数,可通过命名为指定的参数赋值,这称作关键参数,这样指定实参时(调用函数时)是通过名字(关键字)而不是位置来给函数指定实参;这样做有两个好处:不必担心参数的顺序使函数更简单,假设其它参数都有默认值,可只给想要的那些参数赋值)

Return语句(定义函数返回值,一个函数中只能有一个return语句,return可理解为返回并退出;用来从一个函数返回即跳出函数,也可选从函数返回一个值;没有返回值的return语句等价于returnNone,None是python中表示没有任何东西的特殊类型,变量的值为None表示该变量没有值;每个函数都在结尾暗含有return None语句)

Pass在python中表示一个空的语句块,可用于脚本测试,例如:

def somefunction():

pass

docstrings(文档字符串,docstrings是个很重要的工具,可使程序文档更加简单易懂,应尽量使用,甚至可在程序运行时,从函数恢复文档字符串;docstrings惯例是一个多行字符串,首行以大写字母开始,句号结尾,第二行是空行,第三行开始详细的描述,在函数中使用docstrings要遵循这个惯例;可用__doc__调用函数的文档字符串属性,help()所做的就是抓取函数的__doc__属性,格式化输出;docstrings也适用于模块和类)

注:python既是动态类型定义语言(不用声明数据类型),又是强类型定义语言(一旦一个变量具有一个数据类型,实际上就一直是这个类型了)

注:函数是重用的程序段,给一段代码一个名称,程序在任何地方使用这个名称可任意多次运行这段代码这称为调用函数,内建函数如len,range;函数通过关键词def定义,def后跟函数名(函数的标识符名称),函数名后的小括号中是参数(变量名,用逗号分割),整体该行以冒号结尾,之后的是一段语句,这整个是函数体;参数对函数而言只是给函数的输入,以便可传递不同的值给函数

>>> def sayhi():

... print 'hello world'

...

>>> sayhi()

hello world

>>> def info(name,age):

... print 'NAME:%s  AGE:%s' %(name,age)

...

>>> info('jowin',18)

NAME:jowin AGE:18

函数形参、实参举例(形参a和b,将实参3和4赋给形参a和b;printMax(x,y)使用变量调用函数,使实参x和y赋给形参a和b):

[root@localhost ~]# vim func_param.py

-----------script start-----------

#/usr/bin/python

#filename:func_param.py

def printMax(a,b):

if a>b:

print a,'is maximum'

else:

print b,'is maximum'

printMax(3,4)

x=5

y=7

printMax(x,y)

------------script end---------------

[root@localhost ~]# python func_param.py

4 is maximum

7 is maximum

函数局部变量举例:

[root@localhost ~]# vim func_local.py

--------------script start-----------

#!/usr/bin/python

#filename:func_local.py

def func(x):

print 'x is',x

x=2

print 'changed local x to',x

x=50

func(x)

print 'x is still',x

--------------script end--------------

[root@localhost ~]# python func_local.py

x is 50

changed local x to 2

x is still 50

函数全局变量举例:

[root@localhost ~]# vim func_global.py

------------script start-------------

#!/usr/bin/python

#filename:func_global.py

def func():

global x

print 'x is',x

x=2

print 'changed local x to',x

x=50

func()

print 'value of x is',x

------------script end---------------

[root@localhost ~]# python func_global.py

x is 50

changed local x to 2

value of x is 2

函数默认参数举例:

[root@localhost ~]# vim test9.py

-----------script start------------

#!/usr/bin/python

#filename:test9.py

def name_info(name,age,job='Tech'):

print '''%s's information:

NAME:%s

AGE:%s

JOB:%s ''' % (name,name,age,job)

name_info('jowin',18)

---------------script end----------

[root@localhost ~]# python test9.py

jowin's information:

NAME:jowin

AGE:18

JOB:Tech

[root@localhost ~]# vim func_default.py

----------------script start----------------

#!/usr/bin/python

#filename:func_default.py

def say(message,times=1):

print message*times

say('hello')

say('world',5)

-------------script end-------------------

[root@localhost ~]# python func_default.py

hello

worldworldworldworldworld

函数关键参数举例:

[root@localhost ~]# vim func_key.py

------------script start-----------

#!/usr/bin/python

#filename:func_key.py

def func(a,b=5,c=10):

print 'A:%s B:%s  C:%s' % (a,b,c)

return 0

func(3,7)

func(25,c=24)

func(c=50,a=100)

------------script end------------

[root@localhost ~]# python test10.py

A:3 B:7  C:10

A:25 B:5  C:24

A:100 B:5  C:50

函数docstrings举例:

[root@localhost ~]# vim func_doc.py

----------------script start--------------

#!/usr/bin/python

#filename:func_doc.py

def printMax(x,y):

'''prints the maximum of two numbers.

The two values must be integers.'''

x=int(x)

y=int(y)

if x>y:

print x,'is maximum'

else:

print y,'is maximum'

printMax(3,5)

print printMax.__doc__

-------------script end----------------

[root@localhost ~]# python func_doc.py

5 is maximum

prints the maximum of two numbers.

Thetwo values must be integers.

6、文件处理:

[root@localhost ~]# cat contact_list.txt

1     jowin      Tech 13611691019

2     michael   Tech 15000000000

3     scofield   Tech 15111111111

>>> file('contact_list.txt')

<open file 'contact_list.txt', mode 'r'at 0x7fe3c7bb1d20>

>>>file('contact_list.txt').read()

'1\tjowin\tTech\t13611691089\n2\tmichael\tTech\t15000000000\n3\tscofield\tTech\t15111111111\n\n'

>>> file=open('contact_list.txt')

>>> import os,sys,tab

>>> file.

file.__class__(         file.__init__(          file.__str__(           file.isatty(            file.readlines(

file.__delattr__(       file.__iter__(          file.__subclasshook__(  file.mode               file.seek(

file.__doc__            file.__new__(           file.close(             file.name               file.softspace

file.__enter__(         file.__reduce__(        file.closed             file.newlines           file.tell(

file.__exit__(          file.__reduce_ex__(     file.encoding           file.next(              file.truncate(

file.__format__(        file.__repr__(          file.errors             file.read(              file.write(

file.__getattribute__(  file.__setattr__(       file.fileno(            file.readinto(          file.writelines(

file.__hash__(          file.__sizeof__(        file.flush(             file.readline(          file.xreadlines(

>>> file.readline()    (一行一行的读指定文件中的内容

'1\tjowin\tTech\t13611691089\n'

>>> len(file.readline())

27

>>> file.readline()

'3\tscofield\tTech\t15111111111\n'

>>> len(file.readline())

1

>>> file.readline()

''

注:下例中要有退出条件,否则会无限循环

>>> import tab,os,sys

>>> file=open('contact_list.txt')

>>> while True:

... line=file.readline()

... if len(line)==0:break

... print line,

...

1     jowin      Tech 13611691089

2     michael   Tech 15000000000

3     scofield   Tech 15111111111

>>> file.close()    (从内存中清掉打开的文件)

>>> f=file('contact_list.txt')

>>> help(f.tell)   (tell() -> current file position, an integer (may be a longinteger).)

>>> f=open('contact_list.txt')   (打开文件用file或open,open是调用file打开文件的)

>>> help(file)

>>> help(open)

>>> f=file('contact_list.txt','w')  (若文件不存在则创建新文件,若文件存在之后追加的内容将覆盖旧有内容,追加的内容若即时查看则要flush刷写至硬盘,在close关闭此文件之前所有追加的内容都将保存,若关闭了又按w模式打开文件了则之后追加的内容会覆盖掉之前的旧有内容)

注:往一文件中写入,当内容超过1024byte时会自动刷写至磁盘,若内容不足1024byte仍会留在内存,若要实时查看内容则要手动flush,例如在生产环境中若要实时查看日志内容,则要每写一行flush一次,如果不需要实时查看日志则不必每写入都flush

>>> f.write('4 snow Tech15222222222')

>>> f.flush()

>>> os.system('catcontact_list.txt')

4 snow Tech 152222222220

>>> f.write('5 chai Tech15333333333')

>>> f.flush()

>>> os.system('catcontact_list.txt')

4 snow Tech 152222222225 chai Tech153333333330

>>> f=file('contact_list.txt','a')   (若只追加内容,则打开文件时用a,append)

>>> f.write('6 xiang IT15400000000')

>>> f.flush()

>>> os.system('catcontact_list.txt')

4 snow Tech 152222222225 chai Tech153333333336 xiang IT 154000000000

文件内容替换:

for line in fileinput.input(‘filepath’,backup=”.bak”,inplace=1):

line=line.replace(‘oldtext’,’newtext’)

printline,

修改某行:

with open(‘foo.txt’,’r+’) as f:

old=f.read()    #(read everything in the file)

f.seek(0)    #(rewind)

f.write(‘newline\n’+old)    #write the new

line before

pickle、cPickle序列化:

内存里有一个数据结构,希望它保存下来,重用,或发送给其他人,如游戏中允许你在退出时保存进度,当再次启动时会回到上次退出的地方,一个捕获了当前进度的数据结构需要在退出时保存到磁盘上,再重新启动时从磁盘上加载进来

可用pickle模块存储的有:

所有python支持的原生类型,如:布尔、整数、浮点数、复数、字符串、bytes字节串对象、字节数组及None;

由任何原生类型组成的list、tuple、dictionary和集合;

由任何原生类型组成的list、tuple、dictionary、集合组成的list、tuple、dictionary、集合(可一直嵌套下去,直至python支持的最大递归层数);

函数、类、类的实例(带警告)

cPickle与pickle功能相同,只不过cPickle是用C写的效率要高比pickle快1000倍

>>> import cPickle

>>>shoplist=['apple','mango','carrot']

>>> f=file('shoplist.txt','w')

>>> cPickle.dump(shoplist,f)

>>> f.close()

[root@localhost ~]# cat shoplist.txt

(lp1

S'apple'

p2

aS'mango'

p3

aS'carrot'

p4

>>> del shoplist

>>> shoplist

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'shoplist' is not defined

>>> f=file('shoplist.txt')

>>> shoplist=cPickle.load(f)

>>> f.close()

>>> shoplist

['apple', 'mango', 'carrot']

正则表达式:

re.sub函数进行以正则表达式为基础的替换工作,\b表示单词的边界

>>> s='100 NORTH MAIN ROAD'

>>> s.replace('ROAD','RD.')

'100 NORTH MAIN RD.'

>>> s='100 NORTH BROAD ROAD'

>>> s.replace('ROAD','RD.')

'100 NORTH BRD. RD.'

>>> import re

>>> re.sub('ROAD$','RD.',s)

'100 NORTH BROAD RD.'

>>> re.sub(r'\bROAD\b','RD.',s)

'100 NORTH BROAD RD.'

>>> re.sub('[abc]','o','mark')

'mork'

>>> re.sub('[abc]','o','rock')

'rook'

>>>re.sub('[abc]','o','mastash',1)

'mostash'

二、

1、

模块就是包含了定义的函数和变量的文件,这个文件要以.py扩展名结尾;程序要使用模块中的功能要导入import模块,这是使用python标准库的方法

sys(system)模块包含了与python解释器和它环境有关的函数,当执行import sys时将在sys.path变量中所列目录寻找sys.py模块,找到这个模块则此模块主块中的语句被执行,模块中的变量要加点才能使用,例如sys.path,sys.argv

字节编译的文件.pyc(使导入模块速度更快,.pyc文件与平台无关;字节编译的文件与python变换程序的中间状态有关,当下次从其它程序导入该模块时,.pyc文件很有用,会快很多,因为一部分导入模块所需处理已完成)

尽量避免使用from sys import argv,而要使用import sys,这样可使程序更加易读,也可避免名称的冲突

模块的__name__(可用于该模块在单独运行时或在被导入时分别执行不同语句,每个模块都有__name__,如果它是__main__说明它被单独运行,若不是__main__则该模块被导入)

dir()函数(可用内建的dir函数来列出模块定义的标识符,标识符有函数、类、变量,如dir(sys),当为dir提供一个模块时,它返回模块定义的名称列表,若不提供参数它返回当前模块中定义的名称列表

举例:sys.version、sys.path、sys.argv、sys.exit();os.system('uname -a')、os.mkdir('mylist')、os.chdir('~');time.strftime('%Y%m%d');logger.record_log()

导入模块(导入程序块或包,python自带的有内置模块,若想要用其它功能就要导入其它模块,使用方法>>>importMODULE_NAME):

注:模块,可以交互使用的一个代码段,或来自一个大规模的python程序,一旦导入一个模块就可引用它的任何的公共函数、类或属性(格式:>>>MODULE.FUNCTION,例如>>>sys.path)

>>> import sys(导入sys模块使得它的所有函数和属性都有效)

>>> sys.path(模块导入的搜索路径,列出路径,列出的是当前包含的目录,sys.path是一个组成当前搜索路径的目录列表,在导入模块时会按照此路径逐个搜索匹配的*.py文件)

['', '/usr/lib64/python26.zip','/usr/lib64/python2.6', '/usr/lib64/python2.6/plat-linux2','/usr/lib64/python2.6/lib-tk', '/usr/lib64/python2.6/lib-old','/usr/lib64/python2.6/lib-dynload', '/usr/lib64/python2.6/site-packages','/usr/lib64/python2.6/site-packages/gtk-2.0','/usr/lib/python2.6/site-packages', '/usr/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg-info']

注:并非所有模块都保存为*.py文件,如内置模块sys是用C写的源代码不是python所以不是.py文件,sys是置于python内部的

>>> help(sys)

>>> sys.path.append('/root')(自定义加入其它路径)

>>> sys.path

['', '/usr/lib64/python26.zip','/usr/lib64/python2.6', '/usr/lib64/python2.6/plat-linux2','/usr/lib64/python2.6/lib-tk', '/usr/lib64/python2.6/lib-old','/usr/lib64/python2.6/lib-dynload', '/usr/lib64/python2.6/site-packages','/usr/lib64/python2.6/site-packages/gtk-2.0','/usr/lib/python2.6/site-packages','/usr/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg-info', '/root']

使用TAB补全功能:

[root@localhost ~]# vim tab.py

-------------script start---------------

#!/usr/bin/env python

# python startup file

import sys

import readline

import rlcompleter

import atexit

import os

# tab completion

readline.parse_and_bind('tab: complete')

# history file

histfile = os.path.join(os.environ['HOME'],'.pythonhistory')

try:

readline.read_history_file(histfile)

except IOError:

pass

atexit.register(readline.write_history_file,histfile)

del os, histfile, readline, rlcompleter

--------------script end----------------

[root@localhost ~]# python

>>> import sys

>>> import tab(此处只用写名字,无需写后缀.py,注意此处是当前路径,若此脚本在其它位置,要使用绝对路径)

>>> sys.<TAB>

sys.__class__(              sys.exitfunc(

sys.__delattr__(            sys.flags

sys.__dict__                sys.float_info

sys.__displayhook__(        sys.getc

……

>>> sys.version_info

(2, 6, 6, 'final', 0)

>>> import os

>>> os.system('pwd')(调用shell命令)

/root

0

>>> from sys importpath,version_info(直接使用path和version_info,而不是sys.path,sys.version_info这样使用)

>>> path

['', '/usr/lib64/python26.zip','/usr/lib64/python2.6', '/usr/lib64/python2.6/plat-linux2','/usr/lib64/python2.6/lib-tk', '/usr/lib64/python2.6/lib-old','/usr/lib64/python2.6/lib-dynload', '/usr/lib64/python2.6/site-packages','/usr/lib64/python2.6/site-packages/gtk-2.0','/usr/lib/python2.6/site-packages', '/usr/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg-info']

>>> version_info

(2, 6, 6, 'final', 0)

>>> from os import system

>>> system('df -h')

Filesystem            Size  Used Avail Use% Mounted on

/dev/mapper/VolGroup-lv_root

18G  2.4G   15G 15% /

tmpfs                 116M     0  116M   0% /dev/shm

/dev/sda1             485M   33M  427M  8% /boot

/dev/sr0              3.5G  3.5G    0 100% /mnt/cdrom

0

>>> import sys,os(导入多个模块,用逗号分隔)

>>> from sys import version_infoas v(若某个模块的属性很长,可定义别名来使用)

>>> v

(2, 6, 6, 'final', 0)

导入模块举例(当执行#pythonusing_sys.py I am arguments时,python后的所有内容将作为列表传递给sys.argv,依次using_sys.py为sys.argv[0],sys.argv[3]为arguments,脚本名称总是列表的第一个参数;sys.path包含导入模块的目录名列表,第一个空字符表示当前目录这与PYTHONPATH环境变量相同,模块要在sys.path所列的这些目录中否则ImportError):

[root@localhost ~]# vim using_sys.py

----------------scriptstart------------------

#!/usr/bin/python

#filename:using_sys.py

import sys

print 'the command line arguments are:'

for i in sys.argv:

print i

print '\n the PYTHONPATH is:',sys.path,'\n'

-----------------scriptend-----------------

[root@localhost ~]# python using_sys.py Iam arguments

the command line arguments are:

using_sys.py

I

am

arguments

thePYTHONPATH is: ['/root', '/usr/lib64/python26.zip', '/usr/lib64/python2.6','/usr/lib64/python2.6/plat-linux2', '/usr/lib64/python2.6/lib-tk','/usr/lib64/python2.6/lib-old', '/usr/lib64/python2.6/lib-dynload','/usr/lib64/python2.6/site-packages','/usr/lib64/python2.6/site-packages/gst-0.10','/usr/lib64/python2.6/site-packages/gtk-2.0', '/usr/lib64/python2.6/site-packages/webkit-1.0','/usr/lib/python2.6/site-packages']

模块的__name__举例:

[root@localhost ~]# vim using_name.py

-------------------scriptstart--------------

#!/usr/bin/python

#filename:using_name.py

if __name__=='__main__':

print 'this program is being run by itself'

else:

print 'I am being imported from another module.'

------------------scriptend----------------

[root@localhost ~]# python using_name.py

this program is being run by itself

>>> import using_name

I am being imported from another module.

自定义模块(每个python程序.py文件都是一个模块):

[root@localhost ~]# vim mymodule.py

----------------scriptstart-----------------

#!/usr/bin/python

#filename:mymodule.py

def sayhi():

print 'Hi,this is module speaking'

version='0.1'

#End of mymodule.py

------------------scriptend-----------------

>>> import mymodule

>>> mymodule.sayhi()

Hi,this is module speaking

>>> print'VERSION:',mymodule.version

VERSION: 0.1

>>> from mymodule importsayhi,version

>>> sayhi()

Hi,this is module speaking

>>> print 'VERSION:',version

VERSION: 0.1

dir函数举例:

>>> import sys

>>> dir(sys)

['__displayhook__', '__doc__','__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__','__stdout__', '_clear_type_cache', '_current_frames', '_getframe','_mercurial', 'api_version', 'argv', 'builtin_module_names', 'byteorder','call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode','exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable','exit', 'exitfunc', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval','getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile','getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion','last_traceback', 'last_type', 'last_value', 'long_info', 'maxint', 'maxsize','maxunicode', 'meta_path', 'modules', 'path', 'path_hooks','path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning','setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit','settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version','version_info', 'warnoptions']

>>> dir()

['__builtins__', '__doc__', '__name__','__package__', 'sys']

>>> a=18

>>> dir()

['__builtins__', '__doc__', '__name__','__package__', 'a', 'sys']

>>> dir(a)

['__abs__', '__add__', '__and__','__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__','__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__','__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__','__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__','__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__','__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__','__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__','__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__','__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__','__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length','conjugate', 'denominator', 'imag', 'numerator', 'real']

>>> del a

>>> dir()

['__builtins__', '__doc__', '__name__','__package__', 'sys']

2、内置数据类型:dictionary字典、list列表、tuple元组

dictionary定义键和值之间一对一的关系,python中的dictionary象perl的hash哈希数组象java中的hashtable类的实例象vb中的scripting dictionary对象的实例,perl存储哈希值的变量是以%开头,在python中变量可任意取名并在python内部会记录下其数据类型

注:dictionary中的元素key:value,尽量用简单的对象作为key,同时key要用不可变的对象如字符串,value则无此要求;dictionary中的元素是没有顺序的,若要特定的顺序使用前应先排序sort;字典是dict类的对象(实例);用索引操作符[]中括号寻址一个key并为其赋值,用has_key方法检验一个元素key:value是否存在;查看dict类完整方法列表>>>help(dict);使用items方法来使用字典中的每个key和value,它会返回元组的列表,每个元组包含字典中的一个元素

注:函数中的关键字参数就是字典,当在函数中定义变量时,就是使用一个字典的键;编译器设计的术语中称作符号表

(1)定义dictionary用{},此例有两个元素,将两元素赋值给变量d,元素间用逗号分隔,单个元素的key和value之间用冒号分隔且key和value本身用引号引起来,整个元素集合用大括号括起来

>>>d={"server":"mpilgrim","database":"master"}

>>> d

{'database': 'master', 'server':'mpilgrim'}

>>> d.<TAB>

d.__class__(         d.__hash__           d.__setitem__(       d.itervalues(

d.__cmp__(           d.__init__(          d.__sizeof__(        d.keys(

d.__contains__(      d.__iter__(          d.__str__(           d.pop(

d.__delattr__(       d.__le__(            d.__subclasshook__(  d.popitem(

d.__delitem__(       d.__len__(           d.clear(             d.setdefault(

d.__doc__            d.__lt__(            d.copy(              d.update(

d.__eq__(            d.__ne__(            d.fromkeys(          d.values(

d.__format__(        d.__new__(           d.get(               d.viewitems(

d.__ge__(            d.__reduce__(        d.has_key(           d.viewkeys(

d.__getattribute__(  d.__reduce_ex__(     d.items(             d.viewvalues(

d.__getitem__(       d.__repr__(          d.iteritems(

d.__gt__(            d.__setattr__(       d.iterkeys(

>>> d.keys()

['server', 'database']

>>> d.values()

['mpilgrim', 'master']

>>> d.items()

[('server', 'mpilgrim'), ('database','master')]

>>> for server,database ind.items():

... print server,database

...

server mpilgrim

database master

(2)引用一个key所对应的value通过d["server"],只能通过key引用value,不能通过value来获取key

>>> d["server"]

'mpilgrim'

>>> d["database"]

'master'

>>> d["mpilgrim"]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

KeyError: 'mpilgrim'

>>> help(d.has_key)    (True if D has a key k, else False)

>>> d.has_key('server')    (has_key查看有无此key,有则返回布尔值True否则返回False)

True

(3)修改dictionary通过d["server"]="qikai",若key存在则新value会覆盖之前的value,若key不存在则是新添加一个元素,一个dictionary中不能有相同的key,任何时候都可加入新的元素(key:value)这与修改存在的key:value是一样的

>>>d["server"]="qikai"

>>> d

{'database': 'master', 'server': 'qikai'}

>>> d["server"]

'qikai'

>>>d["uid"]="sa"

>>> d

{'database': 'master', 'uid': 'sa','server': 'qikai'}

(4)dictionary中没有元素顺序的概念,只是序偶的简单排列,这是一个重要特性,dictionary中的key是大小写敏感的

>>>d["key"]="value"

>>> d["Key"]="othervalue"

>>> d

{'Key': 'other value', 'database':'master', 'uid': 'sa', 'key': 'value', 'server': 'qikai'}

(5)dictionary中可混用数据类型,value可以是任意数据类型(字符串、整数、对象、甚至可以是其它的dictionary),在单个dictionary中dictionary的value不需要全都是同一数据类型,可根据需要混用;dictionary的key要严格些可以是字符串、整数和几种其它类型(如tuple等)

>>> d["retrycount"]=3

>>> d["42"]="douglas"

>>> d

{'key': 'value', 'uid': 'sa', 'database':'master', '42': 'douglas', 'server': 'qikai','Key': 'other value', 'retrycount': 3}

(6)从dictionary中删除元素,del和pop用于删除独立的元素,clear用于删除所有元素,popitem用于删除第一个元素

>>> d

{'key': 'value', 'uid': 'sa', 'database':'master', '42': 'douglas', 'server': 'qikai','Key': 'other value', 'retrycount': 3}

>>> del d["42"]

>>> d

{'key': 'value', 'uid': 'sa', 'database':'master', 'server': 'qikai', 'Key': 'other value', 'retrycount': 3}

>>> d.clear()

>>> d

{}

>>>d={'server':'qikai','database':'webgame'}

>>> d

{'database': 'webgame', 'server': 'qikai'}

>>> help(d.pop)

>>> d.pop('server')    (pop指定删除某元素)

'qikai'

>>> d

{'database': 'webgame'}

>>>d={'server':'qikai','database':'webgame'}

>>> d

{'database': 'webgame', 'server': 'qikai'}

>>> help(d.popitem)

>>> d.popitem()     (popitem默认删除第一个)

('database', 'webgame')

>>> d

{'server': 'qikai'}

list是python中使用最频繁的数据类型,python中的list象perl和java中的数组,perl中用来保存数组的变量总以@开始,在python中变量可任意取名并在内部会记录其数据类型,python中的list远比java中的数组强大,它可保存任意对象,并可在增加新元素时动态扩展

注:list列表是可变的数据类型(可添加、删除、搜索列表中的条目),列表是使用对象和类的一个例子,如mylist.append('a'),类中定义的函数称作方法method,类中定义的变量称作域field

(1)定义list用[],此例创建5个元素的list,元素间用逗号分隔并保持着初始的顺序,单个元素用双引号引起来,整个元素集合用中括号括起来;list的下标总是从0开始的数组,任何一个非空list的第一个元素是li[0]

>>>li=["a","b","mpilgrim","z","example"]

>>> li

['a', 'b', 'mpilgrim', 'z', 'example']

>>> li[0]

'a'

>>> li[1]

'b'

>>> li[4]

'example'

>>> li.<TAB>

li.__add__(           li.__getslice__(      li.__new__(           li.append(

li.__class__(         li.__gt__(            li.__reduce__(        li.count(

li.__contains__(      li.__hash__           li.__reduce_ex__(     li.extend(

li.__delattr__(       li.__iadd__(          li.__repr__(          li.index(

li.__delitem__(       li.__imul__(          li.__reversed__(      li.insert(

li.__delslice__(      li.__init__(          li.__rmul__(          li.pop(

li.__doc__            li.__iter__(          li.__setattr__(       li.remove(

li.__eq__(            li.__le__(            li.__setitem__(       li.reverse(

li.__format__(        li.__len__(           li.__setslice__(      li.sort(

li.__ge__(            li.__lt__(            li.__sizeof__(

li.__getattribute__(  li.__mul__(           li.__str__(

li.__getitem__(       li.__ne__(            li.__subclasshook__(

reverse *IN PLACE*    (reverse *IN PLACE*)

>>> li.reverse()

>>> li

['example', 'z', 'mpilgrim', 'b', 'a']

>>> li.reverse()

>>> li

['a', 'b', 'mpilgrim', 'z', 'example']

>>> help(li.sort)    (stable sort *IN PLACE*)

>>> li.sort()

>>> li

['a', 'b', 'example', 'mpilgrim', 'z']

>>> li[0]='def'    (改变指定的元素值)

>>> li

['def', 'b', 'example', 'mpilgrim', 'z']

(2)负的list索引,负数索引从list的尾部开始来存取元素,任何一个非空的list最后一个元素总是li[-1],可这样理解li[-n]=li[len(li0-n],在此例中li[-3]=li[2]

>>> li[-1]

'example'

>>> li[-3]

'mpilgrim'

(3)list的分片slice,如li[1:3]指定2个索引得到list的子集叫一个slice,li[1:3]所返回的值是一个新的list,li[1:3]这个子集包含了list中按顺序从第一个slice索引li[1]直到但不包括第二个slice索引li[3]这之间的所有元素,再如li[0:3]从li[0]开始但不包括li[3]这之间的所有元素;slice简写,若左侧分片索引为0可将其省略,例如li[0:3]=li[:3],若右侧分片索引是list的长度,可将其省略,例如li[3:5]=li[3:];注意对称性li[:n]总返回前n个元素,li[n:]将返回剩下的元素,不管list有多长;若将左侧和右侧的两个分片全部省略,这将包括list的所有元素,但与原始的名为li的list不同,它是一个新的list,与原来的li有一样的元素,如li[:]是生成一个list完全拷贝的简写

>>> li[1:3]

['b', 'mpilgrim']

>>> li[0:3]

['a', 'b', 'mpilgrim']

>>> li[:3]

['a', 'b', 'mpilgrim']

>>> li[3:5]

['z', 'example']

>>> li[3:]

['z', 'example']

>>> li[1:-1]

['b', 'mpilgrim', 'z']

>>> li[1:5]

['b', 'mpilgrim', 'z', 'example']

>>> li[1:]

['b', 'mpilgrim', 'z', 'example']

>>> li[:]

['a', 'b', 'mpilgrim', 'z', 'example']

(4)向list中增加元素,append、insert、extend后面紧跟的是()小括号;append向list的末尾追加单个元素;insert将单个元素插入到list中,数值参数是插入点的索引,list中的元素可重复(不必唯一),如此例li[2]和li[6];extend用来连接list,注意不要使用多个参数来调用extend,而要用一个list参数进行调用,在本例中这个list有两个元素

>>> help(li.append)

>>> li.append("new")

>>> li

['a', 'b', 'mpilgrim', 'z', 'example','new']

>>> help(li.insert)

>>> li.insert(2,"new")

>>> li

['a', 'b', 'new', 'mpilgrim', 'z','example', 'new']

>>> li[2]

'new'

>>> li[6]

'new'

>>> help(li.count)    (return number of occurrences of value)

>>> li.count('new')

2

>>> help(li.extend)

>>>li.extend(["two","elements"])

>>> li

['a', 'b', 'new', 'mpilgrim', 'z','example', 'new', 'two', 'elements']

extend与append的差别:

extend接受一个参数,这个参数总是一个list,并且添加这个list中的每个元素到原list中,如下例中len(li)共6个元素;

append接受一个参数,这个参数可以是任何数据类型,只是简单的追加到原list的尾部,如下例使用含有3个元素的list参数调用len(li)共4个元素

>>>li=["a","b","e"]

>>> li

['a', 'b', 'e']

>>>li.extend(["d","e","f"])

>>> li

['a', 'b', 'e', 'd', 'e', 'f']

>>> len(li)

6

>>>li=["a","b","e"]

>>> li

['a', 'b', 'e']

>>>li.append(["d","e","f"])

>>> li

['a', 'b', 'e', ['d', 'e', 'f']]

>>> len(li)

4

>>> li[-1]

['d', 'e', 'f']

(5)在list中搜索:index在list中查找一个值的首次出现并返回索引值,index后紧跟()小括号若在list中没有找到值,python会引发一个异常,这一点与大部分语言截然不同,大部分语言会返回一个无效索引,好处在于在python程序中使用无效索引会引起崩溃;用in可测试一个值是否在list内,如"c" in li,若存在返回True,不存在返回False,注意python中的布尔值True和False第一个字母是大写的,如同python中的其它东西一样是大小写敏感

>>> help(li.index)    (return first index of value)

>>> li.index("b")

1

>>> li.index("e")

2

>>> li.index("example")

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: list.index(x): x not in list

>>> "c" in li

False

>>> "e" in li

True

(6)从list中删除元素:remove从list中删除一个值的首次出现,删除时若没找到值会引发异常来响应index方法,remove后紧跟()小括号;pop删除list的最后一个元素并将删除的值返回(注意做了两件事),li[-1]仅返回一个值但不改变list本身,li.remove("value")改变list但并不返回值

>>> del li[2]   (删除指定的元素)

>>> li.remove("a")

>>> li

['b', 'e', ['d', 'e', 'f']]

>>> li.pop()

['d', 'e', 'f']

>>> li

['b', 'e']

(7)使用list的运算符:可用+运算符连接起来,list=list+other list相当于list.extend(otherlist),+运算符把一个新的list作为值返回(连接后的新的list),而extend只修改存在的list,对于大型list来说,extend的执行速度要快些;+=,如li+=["two"]等同于li.extend(["two"]),+=运算符可用于list、字符串和整数,并且它可以被重载于用户自定义的类中;*可作为一个重复器作用于list,li=[1,2]*3等同于li=[1,2]+[1,2]+[1,2]

>>>li=["a","b","mpilgrim"]

>>> li

['a', 'b', 'mpilgrim']

>>>li=li+["example","new"]

>>> li

['a', 'b', 'mpilgrim', 'example', 'new']

>>> li+=["two"]

>>> li

['a', 'b', 'mpilgrim', 'example', 'new','two']

>>> li=[1,2]*3

>>> li

[1, 2, 1, 2, 1, 2]

(8)映射list,python的强大特性之一是其对list的解析,它提供一种紧凑的方法,可通过对list中的每个元素应用一个函数,从而将一个list映射为另一个list

>>> li=[1,9,8,4]

>>> [elem*2 for elem in li]  (从右向左看便于理解,python循环遍历li中的每个元素,对每个元素均执行elem*2这一函数操作,临时将其值赋给elem,再应用函数elem*2计算,最后将计算结果返回到要返回的list中,对list的解析并不改变原始的list)

[2, 18, 16, 8]

>>> li=[elem*2 for elem in li]

>>> li

[2, 18, 16, 8]

tuple是不可变list,一旦创建了tuple就不能以任何方式改变它,元组和字符串一样是不可变的,通常用在格式化输出的打印语句中和用户定义的函数语句能安全的采用一组值的时候

注:tuple之内的tuple 不会失去它的身份,同理list之中的list、list之中的tuple也不会失去它的身份,若是在perl中会被打散,在python中它们是使用另一个对象存储的对象

注:空元组表示myempty=(),仅含单个元素的元组tuple_single=(2,)注意逗号不可省

注:print的这个用法使输出变得极其简单,避免了许多字符串操作,也避免了使用逗号,没有圆括号只在有一个定制时使用,如print 'why is %s playing with that python' % name

(1)定义tuple与定义list相同,不同之处list的整个元素用[]中括号而tuple的整个元素用()小括号;tuple没有方法,不可以使用append、insert、remove、extend、pop这些方法,但可用index和in用来查找某元素是否存在

tuple的好处,tuple比list操作速度快,如果定义了一个值的常量级,并且唯一要用它做的是不断的遍历它,请使用tuple代替list;

tuple可对不需要修改的数据进行写保护,使得代码更安全,使用tuple如同拥有一个隐含的assert语句,说明这一数据是常量,如果必须要改变这些值,则用到一个特殊的函数执行tuple到list的转换;

tuple可在dictionary中被用作key,但list不行,dictionary的key可以是字符串、整数和其它几种类型,如tuple,dictionary的key的必须是不可变的,tuple本身是不可变的,但如果有一个list的tuple就认为可变若用于dictionary的key就是不安全的,只有字符串、整数和其它对dictionary安全的tuple才可以用作dictionarykey;

tuple可用在字符串格式化中

注:tuple和list可相互转换,内置的tuple函数接收一个list返回一个有相同元素的tuple,内置的list函数接收一个tuple返回一个list,可理解为tuple冻结一个list,list解冻一个tuple

>>>t=("a","b","mpilgrim","z","example")

>>> t

('a', 'b', 'mpilgrim', 'z', 'example')

>>> t.<TAB>   (仅count和index可用)

t.__add__(           t.__getattribute__(  t.__le__(            t.__repr__(

t.__class__(         t.__getitem__(       t.__len__(           t.__rmul__(

t.__contains__(      t.__getnewargs__(    t.__lt__(            t.__setattr__(

t.__delattr__(       t.__getslice__(      t.__mul__(           t.__sizeof__(

t.__doc__            t.__gt__(            t.__ne__(            t.__str__(

t.__eq__(            t.__hash__(          t.__new__(           t.__subclasshook__(

t.__format__(        t.__init__(          t.__reduce__(        t.count(

t.__ge__(            t.__iter__(          t.__reduce_ex__(     t.index(

>>> t[0]

'a'

>>> t[-1]

'example'

>>> t[1:3]

('b', 'mpilgrim')

>>> t.append("new")

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

AttributeError: 'tuple' object has no attribute 'append'

>>> "z" in t

True

>>> t.index("example")

4

>>>t.extend(["new","old"])

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

AttributeError: 'tuple' object has no attribute 'extend'

>>> t.remove("example")

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

AttributeError: 'tuple' object has no attribute 'remove'

>>> t.insert(2,"new")

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

AttributeError: 'tuple' object has no attribute 'insert'

三、三种控制流语句(if、for、while)

raw_input、if…elif…else…、for、while True:、break、continue

注:raw_input() 默认输入是字符串,若要限定仅输入数字需调整int(raw_input());print中’’’CONTENT’’’三引号中的%s,%d,%s是在注释的信息中引用变量,print后的单引号内的%s或%d也是引用外部的变量,print后不管是三引号还是单引号都要跟固定的格式,如print ‘the number is:%d’ % i或print ‘the number is :%d’ % (i)

注:len函数取得一个字符串的长度

注:raw_inpu()是函数用于与用户交互,函数只是重用的代码段

注:脚本中有冒号结尾的表示告诉python下面跟着一个代码块(语句块),代码块中的语句要有正确的缩进,否则语法错误

注:python中引用一范围内的数值为range(1,100)(在shell中是seq 1 100或echo {1..100}),range函数生成序列,默认步长为1,向上到第二个数但不包含第二个数本身,若指定第三个数则为步长,如range(1,5,2)则输出为[1,3]

注:for I inrange(1,5)等价于for I in[1,2,3,4],for…else…中else总是在for循环结束后执行一次,除非遇到break语句

注:True和False为布尔类型,可将其理解为1和0,并非真实的数字1和0,python中的while语句也可用else语句

注:break用来终止循环语句的,哪怕循环条件没有为False或序列尚未完全递归也停止执行循环语句,若在for和while循环中使用break,对应的else块将不执行

注:

脚本使用(用raw_input实现用户交互)

>>> raw_input('please input your name: ')

please input your name: jowin

'jowin'

>>> name=raw_input('please input your name: ')  (给name变量赋值)

please input your name: jowin

>>> name

'jowin'

[root@localhost ~]# vim test1.py

-------------script start------------

#!/usr/bin/enc python

#

name=raw_input('Name:')

age=raw_input('Age:')

job=raw_input('Job:')

print '--------------'

print name,age,job

--------------script end-------------

[root@localhost ~]# python test1.py

Name:jowin

Age:12

Job:yumwei

--------------

jowin 12 yumwei

[root@localhost ~]# vim test1.py

-------------script start----------

#!/usr/bin/enc python

#

name=raw_input('Name:')

age=raw_input('Age:')

job=raw_input('Job:')

print '--------------'

print name,'\n',age,'\n',job

--------------script end------------

[root@localhost ~]# python test1.py

Name:jowin

Age:18

Job:IT

--------------

jowin

18

IT

[root@localhost ~]# vim test1.py

-------------script start-----------

#!/usr/bin/enc python

#

name=raw_input('Name:')

age=raw_input('Age:')

job=raw_input('Job:')

print '--------------'

print'\tNAME:',name,'\n\tAGE:',age,'\n\tJOB:',job

--------------script end-------------

[root@localhost ~]# python test1.py

Name:jowin

Age:22

Job:internet

--------------

NAME:jowin

AGE:22

JOB:internet

[root@localhost ~]# vim test1.py

------------script start-------------

#!/usr/bin/enc python

#

name=raw_input('Name:')

age=int(raw_input('Age:'))

job=raw_input('Job:')

print '--------------'

print type(age)

print '''\tNAME:%s

\tAGE:%d

\tJOB:%s''' %(name,age,job)

---------------script end-------------

注:raw_input() 默认输入是字符串,若要限定仅输入数字需调整int(raw_input());此脚本中’’’CONTENT’’’三引号中的%s,%d,%s是在注释的信息中引用变量

[root@localhost ~]# python test1.py

Name:jowin

Age:23

Job:hehe

--------------

<type 'int'>

NAME:jowin

AGE:23

JOB:hehe

[root@localhost ~]# python test1.py(当Age:处输入不是数字时会报错)

Name:jowin

Age:hehe

Traceback (most recent call last):

File "test1.py", line 4, in <module>

age=int(raw_input('Age:'))

ValueError: invalid literal for int() withbase 10: 'hehe'

脚本使用(流程控制if…else…)

[root@localhost ~]# vim test2.py

-------------script start--------------

#!/usr/bin/env python

#

name=raw_input('please input your name: ')

age=int(raw_input('please input your age:'))

job=raw_input('please input your job: ')

print '--------------'

print '''NAME:%s

AGE:%d

JOB:%s''' %(name,age,job)

if name=='chai':

print "congratulations,you will can have the holiday."

elif age<30:

print "sorry,you will not have the holiday."

else:

print "you can do it as you had sent a gift to your booss."

----------------script end----------------

[root@localhost ~]# python test2.py

please input your name: jowin

please input your age: 22

please input your job: internet

--------------

NAME:jowin

AGE:22

JOB:internet

sorry,you will not have the holiday.

脚本使用(for语句)

>>> for i in range(1,5):

...    print 'the number is:%d' % i

...

the number is:1

the number is:2

the number is:3

the number is:4

>>> for i in range(1,3):

...     print 'the number is:%d' % (i)

...

the number is:1

the number is:2

>>> for i in range(1,5):

...    if i==3:

...             print "good luck,itis:",i

...    print "the number is:%d" % i

...

the number is:1

the number is:2

good luck,it is: 3

the number is:3

the number is:4

[root@localhost ~]# vim test3.py

----------------------scriptstart--------------------

#!/usr/bin/env python

#

while True:

input=raw_input('please input your name: ')

if input=='jowin':

password=raw_input('pleaseinput your password: ')

p='123'

while password!=p:

password=raw_input('wrong password,input again: ')

else:

print "welcomelogin to my territory."

break

else:

print "sorry,user %s notfound " % input

------------------scriptend---------------------------

[root@localhost ~]# python test3.py

please input your name: jowin

please input your password: 123

welcome login to my territory.

[root@localhost ~]# python test3.py

please input your name: chai

sorry,user chai not found

please input your name: haha

sorry,user haha not found

[root@localhost ~]# cat contact_list.txt

1     jowin      Tech 13611691089

2     michael   Tech 15000000000

3     scofield   Tech 15111111111

[root@localhost ~]# vim test4.py

-------------------scriptstart-------------------

#!/usr/bin/python

#filename:test4.py

while True:

input=raw_input('Please input your username:')

if input=='jowin':

password=raw_input('pleaseinput your password:')

p='111'

while password!=p:

password=raw_input('wrong password,input again.')

else:

print 'welcome login to my territory.'

while True:

contact_file=file('contact_list.txt')

match_yes=0

input=raw_input('\033[32mplease input the name whom you want tosearch:\033[0m')

while True:

line=contact_file.readline()

iflen(line)==0:break

if input in line:

print 'match item: \033[32m%s\033[0m' % line

match_yes=1

ifmatch_yes==0:print 'no match item found.'

else:

print 'sorry,user %s not found'% input

-------------------scriptend-----------------------

[root@localhost ~]# python test4.py

Please input your username:jowin

please input your password:111

welcome login to my territory.

please input the name whom you want tosearch:michael

match item: 2  michael   Tech 15000000000

[root@localhost ~]# vim test5.py

-----------------------scriptstart-----------------

#!/usr/bin/env python

#filename:test5.py

import sys,os

f=file('product_list.txt')

products=[]

prices=[]

for line in f.readlines():

new_line=line.split()

products.append(new_line[0])

prices.append(int(new_line[1]))

print products,prices

salary=int(raw_input('please input yoursalary:'))

shop_list=[]

while True:

print 'things have in the shop,please choose one to buy:'

for p in products:

printp,'\t',prices[products.index(p)]

choice=raw_input('please input one item to buy:')

f_choice=choice.strip()

if f_choice in products:

product_price_index=products.index(f_choice)

product_price=prices[product_price_index]

print f_choice,product_price

if salary>product_price:

shop_list.append(f_choice)

print 'added %s intoyour shop list' % f_choice

salary=salary-product_price

print 'salaryleft:',salary

else:

if salary <min(prices):

print'sorry,rest of your salary cannot but anyone'

print 'you havebought these things:%s' % shop_list

sys.exit()

else:

print 'sorry,youcannot afford this'

else:

print 'sorry,%s not in thelist,please try again' % f_choice

-------------------------scriptend-----------------

[root@localhost ~]# python test5.py

['kindle', 'car', 'bicycle'] [1000, 200000,1599]

please input your salary:3000

things have in the shop,please choose oneto buy:

kindle     1000

car  200000

bicycle   1599

please input one item to buy:bicycle

bicycle 1599

added bicycle into your shop list

salary left: 1401

things have in the shop,please choose oneto buy:

kindle     1000

car  200000

bicycle   1599

please input one item to buy:kindle

kindle 1000

added kindle into your shop list

salary left: 401

things have in the shop,please choose oneto buy:

kindle     1000

car  200000

bicycle   1599

please input one item to buy:kindle

kindle 1000

sorry,rest of your salary cannot but anyone

you have bought these things:['bicycle','kindle']

[root@localhost ~]# cat contact_list.txt

4 snow Tech 15222222222

5 chai Tech 15333333333

6 xiang IT 15400000000

[root@localhost ~]# vim test6.py

---------------scriptstart------------------

#!/usr/bin/python

#filename:test6.py

import tab,sys,os

f=file('contact_list.txt')

contact_dic={}

for line in f.readlines():

name=line.split()[1]

contact_dic[name]=line

while True:

input=raw_input('please input the staff name:').strip()

if len(input)==0:continue

if contact_dic.has_key(input):

print '%s' % contact_dic[input]

else:

print 'sorry,no staff namefound'

-------------------scriptend--------------------

[root@localhost ~]# python test6.py

please input the staff name:chai

5 chai Tech 15333333333

please input the staff name:snow

4 snow Tech 15222222222

please input the staff name:xiang

6 xiang IT 15400000000

please input the staff name:hehe

sorry,no staff name found

[root@localhost ~]# vim test7.py

---------------script start--------------

#!/usr/bin/python

#filename:test7.py

import os,sys,tab

def sayhi(n):

print 'hello,%s,how are you' % n

name='jowin'

sayhi(name)

--------------script end---------------

[root@localhost ~]# python test7.py

hello,jowin,how are you

[root@localhost ~]# vim test8.py

----------------script start------------

#!/usr/bin/python

#filename:test8.py

import tab,sys,os

def sayhi(n):

print 'hello,%s,how are you' % n

f=file('contact_list.txt')

for line in f.readlines():

name=line.split()[1]

sayhi(name)

--------------script end-------------

[root@localhost ~]# python test8.py

hello,snow,how are you

hello,chai,how are you

hello,xiang,how are you

[root@localhost ~]# vim expression.py

----------script start------------

#!/usr/bin/python

#filename:expression.py

length=5

breadth=2

area=length*breadth

print 'AREA is:',area

print 'perimeter is:',2*(length+breadth)

----------script end--------------

[root@localhost ~]# python expression.py

AREA is: 10

perimeter is: 14

[root@localhost ~]# vim if.py

------------script start------------

#!/usr/bin/python

#filename:if.py

number=23

guess=int(raw_input('enter your integer:'))

if guess==number:

print 'congratulations,you gueessed it.'

print '(but you do not win any prizes!)'

elif guess<number:

print 'no,it is a little higher than that'

else:

print 'no,it is a little lower than that'

print 'done'

------------script end--------------

[root@localhost ~]# python if.py

enter your integer:25

no,it is a little lower than that

done

[root@localhost ~]# python if.py

enter your integer:23

congratulations,you gueessed it.

(but you do not win any prizes!)

done

[root@localhost ~]# vim while.py

-----------script start------------

#!/usr/bin/python

#filename:while.py

number=23

running=True

while running:

guess=int(raw_input('enter an integer:'))

if guess==number:

print 'congratulations,youguessed it.'

running=False

elif guess<number:

print 'no,it is a littlehighter than that.'

else:

print 'no,it is a little lowerthan that.'

else:

print 'the while hoop is over.'

print 'Done'

--------------scritpt end------------

[root@localhost ~]# python while.py

enter an integer:23

congratulations,you guessed it.

the while hoop is over.

Done

[root@localhost ~]# python while.py

enter an integer:22

no,it is a little highter than that.

enter an integer:24

no,it is a little lower than that.

enter an integer:

[root@localhost ~]# vim for.py

------------script start----------

#!/usr/bin/python

#filename:for.py

for i in range(1,5):

print i

else:

print 'the for loop is over.'

------------scritpt end-----------

[root@localhost ~]# python for.py

1

2

3

4

the for loop is over.

[root@localhost ~]# vim break.py

-----------script start-----------

#!/usr/bin/python

#filename:break.py

while True:

s=raw_input('enter something:')

if s=='quit':

break

print 'length of the string is:',len(s)

print 'done'

-----------script end------------

[root@localhost ~]# python break.py

enter something:jowin

length of the string is: 5

enter something:quit

done

[root@localhost ~]# vim continue.py

-----------script start-----------

#!/usr/bin/python

#filename:continue.py

while True:

s=raw_input('enter something:')

if s=='quit':

break

if len(s)<3:

continue

print 'input is of sufficient length.'

-------------script end-----------

[root@localhost ~]# python continue.py

enter something:jowin

input is of sufficient length.

enter something:c

enter something:c

enter something:chai

input is of sufficient length.

enter something:

python异常处理:

AttributeError(试图访问一个对象没有的属性,如ff.x,ff没有属性x)

IOError(输入输出异常,基本上是无法打开文件)

ImportError(无法导入模块或包,基本上是路径问题或名称错误)

IndentationError(缩进错误,代码没正确对齐)

IndexError(下标索引超出序列边界)

KeyError(字典中不存在的键)

KeyboardInterrupt(按了ctrl+c)

NameError(使用一个未赋值的变量)

SyntaxError(语法错误导致代码不能编译)

TypeError(传入的对象类型与要求的不符合)

UnboundLocalError(局部变量未设置,基本上是有另一个同名的局部变量导致正在访问)

ValueError(传入一个调用者不期望的值)

罗马数字:

I IV4

V5 VI6  VIII8  IX9

X10 XX20  XXI21  XXVIII28 XXX30  XL40

L50 LX60  LXX70  LXXX80 XC90

C100 CC200  CCC300  CD400

D500 DC600  DCC700  DCCC800 CM900

M1000

转载于:https://blog.51cto.com/jowin/1771282

VII python(1)基础知识相关推荐

  1. python编程基础知识体系_最新版 17 幅思维导图:Python 编程之核心知识体系

    原标题:最新版 17 幅思维导图:Python 编程之核心知识体系 导读:本文主要涵盖了 Python 编程的核心知识,展示了一系列思维导图,主要就 Python 核心基础知识进行了细致梳理.无论你是 ...

  2. python代码计算矩形面积_学习资料Python语言基础知识笔记以及答案

    01. Python语言基础知识等笔记: 02. Python作业答案: [例2-3]通过输入函数input()输入股票代码.股票名称.当天股票最高价和最低价,通过输出函数print()输出股票代码+ ...

  3. python基础实例-Python入门基础知识实例,值得收藏!

    7月的编程语言指数榜已经发布,Python 在今年5月首次超越 Java 拿下榜首位置后,仍保持上涨趋势,正逐渐与 Java 拉开差距.(图为与去年 7 月数据对比) 上周为大家简单介绍了如何安装Py ...

  4. python基础实例-Python入门基础知识实例,

    今天小白就为大家分享一些Python的基础知识,希望大家都能快速入门Python~ 1.在Python 语言中,对象是通过引用传递的. 在赋值时,不管这个对象是新创建的,还是一个已经存在的,都是将该对 ...

  5. python基础知识总结-python编程语言基础知识总结

    原标题:python编程语言基础知识总结 今天给大家讲解python语言基础~~ 01.python核心数据类型 整型数 int:整数是不带有小数部分的数字 浮点型数 float:浮点数是带有小数部分 ...

  6. python语法基础知识总结-python语法基础知识

    一.数字类型及操作 1.整数类型 可正可负,无取值范围限制pow(x,y):计算x^y 2.浮点数类型 存在不确定尾数round(x,d):对x四舍五入,d为小数截取位数e/E:a*10^b 3.复数 ...

  7. python笔记基础-Python入门基础知识学习笔记之一

    为什么要写这篇文章? 本人做过Objective-C开发,现在在用C#做WinForm开发.近段时间在学习Python入门基础知识时,发现有很多知识点和Objective-C的不一样.故想通过本文记录 ...

  8. Python入门基础知识学什么?

    Python基础知识主要是针对一些零基础的同学安排的,虽说Python是相对比较简单的一门编程语言,但是没有基础的同学还是要进行系统的学习,那么Python入门基础知识学什么呢?来看看下面小编的详细介 ...

  9. python的基础知识可以应用到哪方面-Python基础知识

    python基础 python的诞生 2002年,python 2.x 2008年,python 3.x python的命名 马戏团的名称 python简介 简单.易学 持快速开发. 跨平台. 开源. ...

  10. post获取重定向的链接 python_【转载】python面试基础知识(四) 网络部分

    最近,小编在整理python面试基础知识,看了很多博客.文章和咨询了一些大厂公司大牛.了解到,在python面试的时候,不仅要求你有项目经验,还要考试代码呢!今天,小编和大家分享一下python面试基 ...

最新文章

  1. 聊一下JVM是如何进行垃圾回收的算法
  2. python开发网页有优势吗_Python用来做Web开发的优势有哪些
  3. Kubernetes1.1源码分析(二)
  4. EASYHOOK逆向寒假生涯(20/100)
  5. ORACLE数据库实现自增的方式
  6. Google浏览器截长图 不需要借助任何插件!!!
  7. 修正IE6不支持position:fixed的bug
  8. Mac上如何重启或结束Finder进程?
  9. gcc对C语言的扩展:标签变量(Labels as Values)
  10. .NET Core 新手上路
  11. 星星之火-47: 5G的八大组网方案
  12. 数据库操作的异常Cannot perform this operation because the connection pool has been close
  13. LeetCode 1240. Tiling a Rectangle with the Fewest Squares
  14. 程序员值得收藏的10大网站 | 推荐指数 | 满天星★★★★★
  15. 【openstack-rally】使用rally执行tempest api测试并导出测试报告
  16. 数据系统架构-6.BI数据展示平台
  17. LU分解Matlab算法分析
  18. 什么叫取反_彻底搞明白“取反加1”到底是个什么鬼?
  19. 【从0到1搭建LoRa物联网】1、LoRa物联网的架构
  20. Linux系统删除文件夹下所有文件

热门文章

  1. 题目1025:最大报销额(动态规划之01背包问题)
  2. 用分支限界法求解01背包
  3. 腾讯技术分享:微服务接口设计原则
  4. 以MacOS 13为例,VMware 16安装MacOS
  5. 【无标题】阳光厨房管理系统需求分析
  6. 阿拉斯加波弗特海,一头北极熊困在渔网险被溺亡
  7. 你好, View Binding! 再次再见, findViewById!
  8. 【树莓派4B】如何烧录新的系统
  9. vue解决Element-ui中 el-cascader 级联选择器 最后一级数据为空显示暂无数据问题
  10. js实现点击按钮图片自动切换_☆往事随風☆的博客