python-十分钟入门
发布日期:2021-10-19 19:33:12 浏览次数:2 分类:技术文章

本文共 36067 字,大约阅读时间需要 120 分钟。

  python十分钟入门

                            简明python教程

【简介】

Python(蟒蛇)是一种动态解释型的编程语言。Python可以在Windows、UNIX、MAC等多种操作系统上使用,也可以在Java、.NET开发平台上使用。

【特点】

1 Python使用C语言开发,但是Python不再有C语言中的指针等复杂的数据类型。

2 Python具有很强的面向对象特性,而且简化了面向对象的实现。它消除了保护类型、抽象类、接口等面向对象的元素。
3 Python代码块使用空格或制表符缩进的方式分隔代码
4 Python仅有31个保留字,而且没有分号、begin、end等标记
5 Python是强类型语言,变量创建后会对应一种数据类型,出现在统一表达式中的不同类型的变量需要做类型转换。

【版本】

python2与python3是目前主要的两个版本。

如下两种情况下,建议使用python2:
1 你无法完全控制你即将部署的环境时;
2 你需要使用一些特定的第三方包或扩展时;
python3是官方推荐的且是未来全力支持的版本,目前很多功能提升仅在python3版本上进行。

【HelloWorld】

1 创建hello.py

2 编写程序:

[python]
  1. #!/usr/bin/python   
  2. # Filename : helloworld.py   
  3.   
  4. if __name__ == '__main__':  
  5.     print 'Hello World'  
#!/usr/bin/python# Filename : helloworld.pyif __name__ == '__main__':    print 'Hello World'
3 运行程序:
[python]
  1. python ./helloworld.py  
python ./helloworld.py

【注释】

1 无论是行注释还是段注释,均以#加一个空格来注释。
2 如果需要在代码中使用中文注释,必须在python文件的最前面加上如下注释说明:

[python]
  1. # -* - coding: UTF-8 -* -  
# -* - coding: UTF-8 -* -

3 如下注释用于指定解释器(它被称作 组织行 ——源文件的头两个字符是#!,后面跟着一个程序。这行告诉你的Linux/Unix系统当你 执行 你的程序的时候,它应该运行哪个解释器)。

[python]
  1. #! /usr/bin/python  
#! /usr/bin/python

4 注意python中也有main函数:

[python]
  1. #hello.py   
  2. def foo():  
  3.     str="function"  
  4.     print(str);  
  5. if __name__=="__main__":  
  6.     print("main")  
  7.     foo()  
#hello.pydef foo():    str="function"    print(str);if __name__=="__main__":    print("main")    foo()
其中if __name__=="__main__":这个程序块类似与Java和C语言的中main(主)函数
在Cmd中运行结果:
[plain]
  1. C:\work\python\divepy>python hello.py  
  2. main  
  3. function  
C:\work\python\divepy>python hello.pymainfunction
在Python Shell中运行结果
[plain]
  1. >>> import hello  
  2. >>> hello.foo()  
  3. function  
  4. >>> hello.__name__  
  5. 'hello'  
  6. >>>  
>>> import hello>>> hello.foo()function>>> hello.__name__'hello'>>>
可以发现这个内置属性__name__自动的发生了变化。
这是由于当你以单个文件运行时,__name__便是__main__。当你以模块导入使用时,这个属性便是这个模块的名字。
5 使用help('print')等可以显示帮助信息。

【文件类型】

1 Python的文件类型分为3种,即源代码、字节代码和优化代码。这些都可以直接运行,不需要进行编译或连接。
2 源代码以.py为扩展名,由python来负责解释;
3 源文件经过编译后生成
扩展名为.pyc的文件,即
编译过的字节文件。这种文件
不能使用文本编辑器修改。pyc文件是和
平台无关的,可以在大部分操作系统上运行。如下语句可以用来产生pyc文件:

[python]
  1. import py_compile  
  2. py_compile.compile(‘hello.py’)  
import py_compilepy_compile.compile(‘hello.py’)
4 经过优化的源文件会以.pyo为后缀,即优化代码。它也不能直接用文本编辑器修改,如下命令可用来生成pyo文件:
[python]
  1. python -O -m py_complie hello.py  
python -O -m py_complie hello.py

【变量】

1 python中的变量不需要声明,变量的赋值操作即使变量声明和定义的过程。
2 python中一次新的赋值,将创建一个新的变量。即使变量的名称相同,变量的标识并不相同。用
id()函数可以获取变量标识
[python]
  1. x = 1  
  2. print id(x)  
  3. x = 2  
  4. print id(x)  
x = 1print id(x)x = 2print id(x)
3 如果变量没有赋值,则python认为该变量不存在
4 在函数之外定义的变量都可以称为全局变量。全局变量可以被文件内部的任何函数和外部文件访问。
5 全局变量建议在文件的开头定义。
6
也可以把全局变量放到一个专门的文件中,然后通过import来引用
gl.py文件中内容如下:
[python]
  1. _a = 1  
  2. _b = 2  
_a = 1_b = 2
use_global.py中引用全局变量:
[python]
  1. import gl  
  2. def fun():  
  3.   print gl._a  
  4.   print gl._b  
  5. fun()  
import gldef fun():  print gl._a  print gl._bfun()

【常量】

python中没有提供定义常量的保留字。
可以自己定义一个常量类来实现常量的功能
[python]
  1. class _const:  
  2.   class ConstError(TypeError): pass  
  3.     def __setattr__(self,name,vlaue):  
  4.       if self.__dict__.has_key(name):  
  5.         raise self.ConstError, “Can’t rebind const(%s)”%name  
  6.         self.__dict__[name]=value  
  7. import sys  
  8. sys.modules[__name__]=_const()  
class _const:  class ConstError(TypeError): pass    def __setattr__(self,name,vlaue):      if self.__dict__.has_key(name):        raise self.ConstError, “Can’t rebind const(%s)”%name        self.__dict__[name]=valueimport syssys.modules[__name__]=_const()

注意浮点数:

3.23和52.3E-4是浮点数的例子。E标记表示10的幂。在这里,52.3E-4表示52.3 * 10-4。

(-5+4j)和(2.3-4.6j)是复数的例子。

注意字符串:

使用单引号(')你可以用单引号指示字符串,就如同'Quote me on this'这样。所有的空白,即空格和制表符都照原样保留。

使用双引号(")在双引号中的字符串与单引号中的字符串的使用完全相同,例如"What's your name?"。
使用三引号('''或""")利用三引号,你可以指示一个多行的字符串。你可以在三引号中自由的使用单引号和双引号。

注意字符串中的转义字符:

用\'来指示单引号——注意这个反斜杠。现在你可以把字符串表示为'What\'s your name?'。另一个表示这个特别的字符串的方法是"What's your name?",即用双引号。另外,你可以用转义符\\来指示反斜杠本身。

自然字符串:

如果你想要指示某些不需要如转义符那样的特别处理的字符串,那么你需要指定一个自然字符串。自然字符串通过给字符串加上前缀r或R来指定。例如r"Newlines are indicated by \n"。

Unicode字符串:

Python允许你处理Unicode文本——你只需要在字符串前加上前缀u或U。例如,u"This is a Unicode string."。

【数据类型】

1 python的数字类型分为整型、长整型、浮点型、布尔型、复数类型。
2 python没有字符类型
3 python内部没有普通类型,
任何类型都是对象
4 如果需要
查看变量的类型,可以使用type类,该类可以返回变量的类型或创建一个新的类型。
5 python有3种表示字符串类型的方式,即单引号、双引号、三引号。单引号和双引号的作用是相同的。python程序员更喜欢用单引号,C/Java程序员则习惯使用双引号表示字符串。三引号中可以输入单引号、双引号或换行等字符。

【类型转换】

 int(x [,base ])         将x转换为一个整数

 long(x [,base ])         将x转换为一个长整数
 float(x )               将x转换到一个浮点数
 complex(real [,imag ])  创建一个复数
 str(x )                 将对象 x 转换为字符串
 repr(x )                 将对象 x 转换为表达式字符串
 eval(str )             用来计算在字符串中的有效Python表达式,并返回一个对象
 tuple(s )               将序列 s 转换为一个元组
 list(s )                 将序列 s 转换为一个列表
 chr(x )                 将一个整数转换为一个字符
 unichr(x )               将一个整数转换为Unicode字符
 ord(x )                 将一个字符转换为它的整数值
 hex(x )                 将一个整数转换为一个十六进制字符串
 oct(x )                 将一个整数转换为一个八进制字符串

【运算符和表达式】

1 python不支持自增运算符和自减运算符。例如
i++/i–是错误的,但i+=1是可以的
2
1/2在python2.5之前会等于0.5,在python2.5之后会等于0
3
不等于为!=或<>
4
等于用==表示
5 逻辑表达式中and表示逻辑与,or表示逻辑或,not表示逻辑非

6 exec和eval语句

exec语句用来执行储存在字符串或文件中的Python语句。例如,我们可以在运行时生成一个包含Python代码的字符串,然后使用exec语句执行这些语句。下面是一个简单的例子。
[python]
  1. >>> exec 'print "Hello World"'  
  2. Hello World  
>>> exec 'print "Hello World"'Hello World
eval语句用来计算存储在字符串中的有效Python表达式。下面是一个简单的例子。
[python]
  1. >>> eval('2*3')  
  2. 6  
>>> eval('2*3')6

【控制语句】

1 条件语句:

[python]
  1. if (表达式) :#其实表达式可以没有括号   
  2.     语句1  
  3. else :  
  4.     语句2  
if (表达式) :#其实表达式可以没有括号    语句1else :    语句2

2 条件语句:

[python]
  1. if (表达式) :  
  2.   语句1  
  3. elif (表达式) :  
  4.   语句2  
  5. …  
  6. elif (表达式) :  
  7.   语句n  
  8. else :  
  9.   语句m  
if (表达式) :  语句1elif (表达式) :  语句2…elif (表达式) :  语句nelse :  语句m

3 条件嵌套:

[python]
  1. if (表达式1) :  
  2.   if (表达式2) :  
  3.     语句1  
  4.   elif (表达式3) :  
  5.     语句2  
  6.   …  
  7.   else:  
  8.     语句3  
  9. elif (表达式n) :  
  10.    …  
  11. else :  
  12.    …  
if (表达式1) :  if (表达式2) :    语句1  elif (表达式3) :    语句2  …  else:    语句3elif (表达式n) :   …else :   …

4 python本身没有switch语句。
5 循环语句:

[python]
  1. while(表达式) :  
  2.    …  
  3. else :  
  4.    …  
while(表达式) :   …else :   …

6 循环语句:

[python]
  1. for 变量 in 集合 :  
  2.    …  
  3. else :  
  4.    …  
for 变量 in 集合 :   …else :   …

7 range:

python不支持类似c的for(i=0;i<5;i++)这样的循环语句,但可以借助range模拟:
[python]
  1. for x in range(0,5,2):  
  2.     print x  
for x in range(0,5,2):    print x

range(1,5)给出序列[1, 2, 3, 4]

range(1,5,2)给出[1,3]

举例:

[python]
  1. #!/usr/bin/python   
  2. # Filename: while.py   
  3.   
  4. number = 23  
  5. running = True  
  6.   
  7. while running:  
  8.     guess = int(raw_input('Enter an integer : '))  
  9.   
  10.     if guess == number:  
  11.         print 'Congratulations, you guessed it.'   
  12.         running = False # this causes the while loop to stop   
  13.     elif guess < number:  
  14.         print 'No, it is a little higher than that'   
  15.     else:  
  16.         print 'No, it is a little lower than that'   
  17. else:  
  18.     print 'The while loop is over.'   
  19.     # Do anything else you want to do here   
  20.   
  21. print 'Done'  
#!/usr/bin/python# Filename: while.pynumber = 23running = Truewhile running:    guess = int(raw_input('Enter an integer : '))    if guess == number:        print 'Congratulations, you guessed it.'         running = False # this causes the while loop to stop    elif guess < number:        print 'No, it is a little higher than that'     else:        print 'No, it is a little lower than that' else:    print 'The while loop is over.'     # Do anything else you want to do hereprint 'Done'

8 break和continue

[java]
  1. #!/usr/bin/python  
  2. # Filename: continue.py  
  3.   
  4. while True:  
  5.     s = raw_input('Enter something : ')  
  6.     if s == 'quit':  
  7.         break  
  8.     if len(s) < 3:  
  9.         continue  
  10.     print 'Input is of sufficient length'  
  11.     # Do other kinds of processing here...  
#!/usr/bin/python# Filename: continue.pywhile True:    s = raw_input('Enter something : ')    if s == 'quit':        break    if len(s) < 3:        continue    print 'Input is of sufficient length'    # Do other kinds of processing here...

9 三元操作符

[python]
  1. V1 if X else V2  
V1 if X else V2
完美的解决方案是在《python核心编程中提到的》:

如果你来自 C/C++ 或者是 Java 世界, 那么你很难忽略的一个事实就是 Python 在很长的一段时间里没有条件表达式(C ? X : Y), 或称三元运算符. ( C 是条件表达式; X 是 C 为 True 时的结果, Y 是 C 为 False 时的结果) 

贵铎·范·罗萨姆一直拒绝加入这样的功能, 因为他认为应该保持代码简单, 让程序员不轻易出错. 不过在十年多后, 他放弃了, 主要是因为人们试着用and 和 or 来模拟它, 但大多都是错误的. 根据 FAQ , 正确的方法(并不唯一)是(C and [X] or [Y])[0] .

唯一的问题是社区不同意这样的语法. (你可以看一看 PEP 308, 其中有不同的方案.) 对于Python 的这一问题,人们表达了极大的诉求.贵铎·范·罗萨姆最终选择了一个最被看好(也是他最喜欢)的方案, 然后把它运用于标准库中的一些模块. 根据 PEP , "这个评审通过考察大量现实世界的案例, 包含不同的应用, 以及由不同程序员完成的代码." 最后 Python 2.5 集成的语法确定为: X if C else Y .

【数据结构】

1 元组(tuple)

[python]
  1. tuple_name=("apple",5,tuple,"orange")  
tuple_name=("apple",5,tuple,"orange")
解释:tuple[2]

python中一种内置的数据结构。元组由不同的元素组成,每个元素可以存储不同类型的数据,如字符串、数字甚至元素。元组是写保护的,即元组创建之后不能再修改。元组往往代表一行数据,而元组中的元素代表不同的数据项。可以把元组看做不可修改的数组。创建元组示例如下:

[python]
  1. tuple_name=("apple",5,tuple,"orange")  
tuple_name=("apple",5,tuple,"orange")

我们可以通过一对方括号来指明某个项目的位置从而来访问元组中的项目,就像我们对列表的用法一样。这被称作 索引 运算符。我们使用new_zoo[2]来访问new_zoo中的第三个项目。我们使用new_zoo[2][2]来访问new_zoo元组的第三个项目的第三个项目。

含有0个或1个项目的元组:

一个空的元组由一对空的圆括号组成,如myempty = ()。然而,含有单个元素的元组就不那么简单了。你必须在第一个(唯一一个)项目后跟一个逗号,这样Python才能区分元组和表达式中一个带圆括号的对象。即如果你想要的是一个包含项目2的元组的时候,你应该指明singleton = (2 , )。

元组基本上同列表,但不同的是元组用圆括号表示,元组中的值不可以改变,相当于一个常量。

2 列表(list)

[python]
  1. list=["apple","banana","grage","orange"]  
list=["apple","banana","grage","orange"]
解释:list[2]

列表和元组相似,也由一组元素组成,列表可以实现添加、删除和查找操作,元素的值可以被修改。列表是传统意义上的数组。列表创建示例如下:

[python]
  1. list=["apple","banana","grage","orange"]  
list=["apple","banana","grage","orange"]

使用:

可以使用append方法来在尾部追加元素,使用remove来删除元素。

[python]
  1. # -* - coding: UTF-8 -* -   
  2. #!/usr/bin/python   
  3. # Filename: using_list.py   
  4.   
  5. list = ['apple''mango''carrot''banana']  
  6.   
  7. #列表长度   
  8. len(list)  
  9.   
  10. #遍历列表   
  11. # 注意末尾的逗号,我们在print语句的结尾使用了一个 逗号 来消除每个print语句自动打印的换行符。这样做有点难看,不过确实简单有效。   
  12. print 'These items are:',  
  13. for item in list:  
  14.     print item,  
  15.   
  16. #增加列表项   
  17. list.append('rice')  
  18.   
  19. #列表排序   
  20. #注意sort()函数改变原来的列表,函数返回值是空值即None   
  21. list.sort()  
  22. #获得排序列表副本1   
  23. list2 = list[:]  
  24. list2.sort()  
  25. #获得排序列表副本2   
  26. list3 = sorted(list)  
  27.   
  28. #删除列表项   
  29. del list[0]  
# -* - coding: UTF-8 -* -#!/usr/bin/python# Filename: using_list.pylist = ['apple', 'mango', 'carrot', 'banana']#列表长度len(list)#遍历列表# 注意末尾的逗号,我们在print语句的结尾使用了一个 逗号 来消除每个print语句自动打印的换行符。这样做有点难看,不过确实简单有效。print 'These items are:',for item in list:    print item,#增加列表项list.append('rice')#列表排序#注意sort()函数改变原来的列表,函数返回值是空值即Nonelist.sort()#获得排序列表副本1list2 = list[:]list2.sort()#获得排序列表副本2list3 = sorted(list)#删除列表项del list[0]

特别注意,在列表的排序中:
1,list.sort()是对本身进行排序,返回None;
2,list2 = sorted(list)是排序后返回副本,不影响原数据。
特别的:
内置的sorted()函数:sorted(iterable[, cmp[, key[, reverse]]])
(1)iterable:是可迭代类型类型;
(2)cmp:用于比较的函数,比较什么由key决定,有默认值,迭代集合中的一项;
(3)key:用列表元素的某个属性和函数进行作为关键字,有默认值,迭代集合中的一项;
(4)reverse:排序规则. reverse = True 或者 reverse = False,有默认值,默认为升序排列(False)。

帮助:

可以通过help(list)获得完整的知识。

3 字典(dictionary)

[python]
  1. dict={
    "a":"apple""b":"banana""g":"grage""o":"orange"}  
dict={"a":"apple", "b":"banana", "g":"grage", "o":"orange"}
解释:

由键-值对组成的集合,字典中的值通过键来引用。键和值之间用冒号隔开,键-值对之间用逗号隔开,并且被包含在一对花括号中。注意,键必须是唯一的。记住字典中的键/值对是没有顺序的。字典是dict类的实例/对象。创建示例如下:

[python]
  1. dict={
    "a":"apple""b":"banana""g":"grage""o":"orange"}  
dict={"a":"apple", "b":"banana", "g":"grage", "o":"orange"}

使用:dict[key]

[python]
  1. # -* - coding: UTF-8 -* -   
  2. #!/usr/bin/python   
  3. # Filename: using_dict.py   
  4.   
  5. addressBook = {  
  6.              'Swaroop'   : 'swaroopch@byteofpython.info',  
  7.              'Larry'     : 'larry@wall.org',  
  8.              'Matsumoto' : 'matz@ruby-lang.org',  
  9.              'Spammer'   : 'spammer@hotmail.com'  
  10.      }  
  11. # 使用字典:dict[key]   
  12. print "Swaroop's address is %s" % addressBook['Swaroop']  
  13.   
  14. # 增加字典项:dict[newKey]=newValue   
  15. addressBook['Guido'] = 'guido@python.org'  
  16.   
  17. # 删除字典项:del dict[key]   
  18. del addressBook['Spammer']  
  19.   
  20. # 字典长度:len(dict)   
  21. print '\nThere are %d contacts in the address-book\n' % len(addressBook)  
  22.   
  23. # 遍历字典:   
  24. for name, address in addressBook.items():  
  25.     print 'Contact %s at %s' % (name, address)  
  26. # 查找字典值:   
  27. if 'Guido' in addressBook: # 或 addressBook.has_key('Guido')   
  28.     print "\nGuido's address is %s" % addressBook['Guido']  
  29.   
  30. #对字典按键排序,元组列表的形式返回   
  31. d={
    "ok":1,"no":2}  
  32. sorted(d.items, key=lambda d:d[0])  
  33. #[('no', 2), ('ok', 1)]   
  34.   
  35. 对字典按值排序,元组列表的形式返回  
  36. d={
    "ok":1,"no":2}  
  37. sorted(d.items, key=lambda d:d[1])  
  38. #[('ok', 1), ('no', 2)]  
# -* - coding: UTF-8 -* -#!/usr/bin/python# Filename: using_dict.pyaddressBook = {             'Swaroop'   : 'swaroopch@byteofpython.info',             'Larry'     : 'larry@wall.org',             'Matsumoto' : 'matz@ruby-lang.org',             'Spammer'   : 'spammer@hotmail.com'     }# 使用字典:dict[key]print "Swaroop's address is %s" % addressBook['Swaroop']# 增加字典项:dict[newKey]=newValueaddressBook['Guido'] = 'guido@python.org'# 删除字典项:del dict[key]del addressBook['Spammer']# 字典长度:len(dict)print '\nThere are %d contacts in the address-book\n' % len(addressBook)# 遍历字典:for name, address in addressBook.items():    print 'Contact %s at %s' % (name, address)# 查找字典值:if 'Guido' in addressBook: # 或 addressBook.has_key('Guido')    print "\nGuido's address is %s" % addressBook['Guido']#对字典按键排序,元组列表的形式返回d={"ok":1,"no":2}sorted(d.items, key=lambda d:d[0])#[('no', 2), ('ok', 1)]对字典按值排序,元组列表的形式返回d={"ok":1,"no":2}sorted(d.items, key=lambda d:d[1])#[('ok', 1), ('no', 2)]

帮助:

可以通过help(dict)获得完整的知识。

4 序列

解释:

1,列表元组字符串都是序列。

2,序列的两个主要特点是索引操作符和切片操作符。

索引操作符让我们可以从序列中抓取一个特定项目。

切片操作符让我们能够获取序列的一个切片,即一部分序列。

使用:

shoplist[0]抓取第一个项目,shoplist[3]抓取shoplist序列中的第四个元素。
shoplist[-1]表示序列的最后一个元素而shoplist[-2]抓取序列的倒数第二个项目。
shoplist[1:3]返回从位置1开始,包括位置2,但是停止在位置3的一个序列切片,因此返回一个含有两个项目的切片。
shoplist[:]返回整个序列的拷贝。
shoplist[:-1]会返回除了最后一个项目外包含所有项目的序列切片。

[python]
  1. #!/usr/bin/python   
  2. # Filename: seq.py   
  3.   
  4. shoplist = ['apple''mango''carrot''banana']  
  5.   
  6. # Indexing or 'Subscription' operation   
  7. print 'Item 0 is', shoplist[0]  
  8. print 'Item 1 is', shoplist[1]  
  9. print 'Item 2 is', shoplist[2]  
  10. print 'Item 3 is', shoplist[3]  
  11. print 'Item -1 is', shoplist[-1]  
  12. print 'Item -2 is', shoplist[-2]  
  13.   
  14. # Slicing on a list   
  15. print 'Item 1 to 3 is', shoplist[1:3]  
  16. print 'Item 2 to end is', shoplist[2:]  
  17. print 'Item 1 to -1 is', shoplist[1:-1]  
  18. print 'Item start to end is', shoplist[:]  
  19.   
  20. # Slicing on a string   
  21. name = 'swaroop'  
  22. print 'characters 1 to 3 is', name[1:3]  
  23. print 'characters 2 to end is', name[2:]  
  24. print 'characters 1 to -1 is', name[1:-1]  
  25. print 'characters start to end is', name[:]  
#!/usr/bin/python# Filename: seq.pyshoplist = ['apple', 'mango', 'carrot', 'banana']# Indexing or 'Subscription' operationprint 'Item 0 is', shoplist[0]print 'Item 1 is', shoplist[1]print 'Item 2 is', shoplist[2]print 'Item 3 is', shoplist[3]print 'Item -1 is', shoplist[-1]print 'Item -2 is', shoplist[-2]# Slicing on a listprint 'Item 1 to 3 is', shoplist[1:3]print 'Item 2 to end is', shoplist[2:]print 'Item 1 to -1 is', shoplist[1:-1]print 'Item start to end is', shoplist[:]# Slicing on a stringname = 'swaroop'print 'characters 1 to 3 is', name[1:3]print 'characters 2 to end is', name[2:]print 'characters 1 to -1 is', name[1:-1]print 'characters start to end is', name[:]

5 列表综合

解释:

通过列表综合,可以从一个已有的列表导出一个新的列表。例如,你有一个数的列表,而你想要得到一个对应的列表,使其中所有大于2的数都是原来的2倍。对于这种应用,列表综合是最理想的方法。

[python]
  1. # -* - coding: UTF-8 -* -   
  2. #!/usr/bin/python   
  3. # Filename: list_comprehension.py   
  4.   
  5. listone = [234]  
  6. listtwo = [2*i for i in listone if i > 2]  
  7. print listtwo  # 结果是[6,8]  
# -* - coding: UTF-8 -* -#!/usr/bin/python# Filename: list_comprehension.pylistone = [2, 3, 4]listtwo = [2*i for i in listone if i > 2]print listtwo  # 结果是[6,8]

【函数相关】

1,解释

python程序由包(package)模块(module)函数组成。包是由一系列模块组成的集合。模块是处理某一类问题的函数和类的集合。包就是一个完成特定任务的工具箱。包必须含有一个__init__.py文件,它用于标识当前文件夹是一个包。python的程序是由一个个模块组成的。模块把一组相关的函数或代码组织到一个文件中,一个文件即是一个模块。模块由代码、函数和类组成。导入模块使用import语句。包的作用是实现程序的重用。函数是一段可以重复多次调用的代码。

通常把内建函数成为BIF(built-in functions)

2,定义

函数定义示例如下:

[python]
  1. #!/usr/bin/python   
  2. # Filename: seq.py   
  3.   
  4. def arithmetic(x,y,operator):  
  5.    result={  
  6.       "+":x+y,  
  7.       "-":x-y,  
  8.       "*":x*y,  
  9.       "/":x/y  
  10.    }  
  11.    return result[operator]  
  12.   
  13. print arithmetic(1,2,"+")  
#!/usr/bin/python# Filename: seq.pydef arithmetic(x,y,operator):   result={      "+":x+y,      "-":x-y,      "*":x*y,      "/":x/y   }   return result[operator]print arithmetic(1,2,"+")
函数返回值可以用return来控制,
除非你提供你自己的return语句,每个函数都在结尾暗含有return None语句

3,变量

函数内部的全局变量

[python]
  1. #!/usr/bin/python   
  2. # Filename: func_global.py   
  3.   
  4. def func():  
  5.     global x #这里声明使用外部定义的全局的x。   
  6.   
  7.     print 'x is', x  #将输出外部值50   
  8.     x = 2  
  9.     print 'Changed local x to', x #这里外部值x真正的被改变了   
  10.   
  11. x = 50  
  12. func()  
  13. print 'Value of x is', x  
#!/usr/bin/python# Filename: func_global.pydef func():    global x #这里声明使用外部定义的全局的x。    print 'x is', x  #将输出外部值50    x = 2    print 'Changed local x to', x #这里外部值x真正的被改变了x = 50func()print 'Value of x is', x

4, DocStrings

文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开始是详细的描述。 强烈建议 你在你的函数中使用文档字符串时遵循这个惯例。

  pass语句在Python中表示一个空的语句块。

[python]
  1. # -* - coding: UTF-8 -* -   
  2. #!/usr/bin/python   
  3. # Filename: func_doc.py   
  4.   
  5. #这里的y=1是默认参数   
  6. def func(x, y=1):  
  7.     '''''This is the DocStrings 
  8.  
  9.  
  10.        func(x,y=1) '''  
  11.     pass #这句表示空语句   
  12.   
  13. print func(3)       #由于函数没有return的话默认有一句 return None,所以这里输出None   
  14. print func.__doc__  #这里调用直接输出DocStrings  
# -* - coding: UTF-8 -* -#!/usr/bin/python# Filename: func_doc.py#这里的y=1是默认参数def func(x, y=1):    '''This is the DocStrings       func(x,y=1) '''    pass #这句表示空语句print func(3)       #由于函数没有return的话默认有一句 return None,所以这里输出Noneprint func.__doc__  #这里调用直接输出DocStrings

如果要打印本文件而不是其他模块的docString,我想出来了这么一个办法:

A.py

[python]
  1. ''''' 
  2. Created on 2012-10-10 
  3. @author: xing.gexing 
  4. '''  
  5. import A  
  6.   
  7. if __name__=="__main__":  
  8.     print A.__doc__  
'''Created on 2012-10-10@author: xing.gexing'''import Aif __name__=="__main__":    print A.__doc__

5,导入模块

如果你想要直接输入argv变量到你的程序中(避免在每次使用它时打sys.),那么你可以使用from sys import argv语句。如果你想要输入所有sys模块使用的名字,那么你可以使用from sys import *语句。这对于所有模块都适用。一般说来,应该避免使用from..import而使用import语句,因为这样可以使你的程序更加易读,也可以避免名称的冲突。也可以直接import sys

6, 创建模块

创建如下模块:mymodule.py

[python]
  1. #!/usr/bin/python   
  2. # Filename: mymodule.py   
  3.   
  4. def sayhi():  
  5.     print 'Hi, this is mymodule speaking.'  
  6.   
  7. version = '0.1'  
  8.   
  9. # End of mymodule.py  
#!/usr/bin/python# Filename: mymodule.pydef sayhi():    print 'Hi, this is mymodule speaking.'version = '0.1'# End of mymodule.py
测试用例1:mymodule_demo.py

[python]
  1. #!/usr/bin/python   
  2. # Filename: mymodule_demo.py   
  3.   
  4. import mymodule  
  5.   
  6. mymodule.sayhi()  
  7. print 'Version', mymodule.version  
#!/usr/bin/python# Filename: mymodule_demo.pyimport mymodulemymodule.sayhi()print 'Version', mymodule.version
测试用例2:mymodule_demo.py

[python]
  1. #!/usr/bin/python   
  2. # Filename: mymodule_demo2.py   
  3.   
  4. from mymodule import sayhi, version  
  5. # Alternative:   
  6. # from mymodule import *   
  7.   
  8. sayhi()  
  9. print 'Version', version  
#!/usr/bin/python# Filename: mymodule_demo2.pyfrom mymodule import sayhi, version# Alternative:# from mymodule import *sayhi()print 'Version', version

7,函数中传入元组、列表、字典

元组、列表: 当要使函数接收元组或字典形式的参数的时候,有一种特殊的方法,它分别使用*和**前缀。这种方法在函数需要获取可变数量的参数的时候特别有用。

字典: 由于在args变量前有*前缀,所有多余的函数参数都会作为一个元组存储在args中。如果使用的是**前缀,多余的参数则会被认为是一个字典的键/值对。

[python]
  1. # -* - coding: UTF-8 -* -   
  2. #!/usr/bin/python   
  3.   
  4.   
  5. # 1,函数的参数是元组/列表   
  6. #   后续参数1,2作为元组(1,2)传入   
  7. def a1(*args):  
  8.     if len(args)==0:  
  9.         print 'None'  
  10.     else:  
  11.         print args  
  12. a1()         # 输出None   
  13. a1(1,2)      # 输出(1, 2)   
  14.   
  15.   
  16. # 2,函数的参数是字典   
  17. #   后续参数作为字典{x:1,y:2}传入   
  18. def a2(**args):  
  19.     if len(args)==0:  
  20.         print 'None'  
  21.     else:  
  22.         print args  
  23. a2()         # 输出None   
  24. a2(x=1,y=2)  # 输出{'y': 2, 'x': 1}注意遍历返回的顺序与形参位置顺序相反<SPAN style="TEXT-ALIGN: left; LINE-HEIGHT: 26px; FONT-FAMILY: Arial; COLOR: rgb(51,51,51); FONT-SIZE: 14px"></SPAN>  
# -* - coding: UTF-8 -* -#!/usr/bin/python# 1,函数的参数是元组/列表#   后续参数1,2作为元组(1,2)传入def a1(*args):    if len(args)==0:        print 'None'    else:        print argsa1()         # 输出Nonea1(1,2)      # 输出(1, 2)# 2,函数的参数是字典#   后续参数作为字典{x:1,y:2}传入def a2(**args):    if len(args)==0:        print 'None'    else:        print argsa2()         # 输出Nonea2(x=1,y=2)  # 输出{'y': 2, 'x': 1}注意遍历返回的顺序与形参位置顺序相反

另外特别地,对于传递字典,有这样一些结论:

[python]
  1. #dict1={x:1,y:2} # NameError: name 'x' is not defined,除非这个x变量事先已经被定义了。   
  2. dict2={
    'x':1,'y':2}  
  3. #dict3={1:x,2:y} # NameError: name 'x' is not defined,同理。   
  4. dict4={
    1:'x',2:'y'}  
  5.   
  6. # 定义函数参数为字典   
  7. def a(**args):  
  8.     print args  
  9.   
  10. a(x=1,y=2)      # 我的理解是,这里估计先要通过函数的语法检查,所以=左边必须是变量,然后才被识别为字符串'x',所以这种传递字典很局限,只能传递key为字符串的字典。   
  11. #a('x'=1,'y'=2)   
  12. #a(1=x,2=y)   
  13. #a(1='x',2='y')  
#dict1={x:1,y:2} # NameError: name 'x' is not defined,除非这个x变量事先已经被定义了。dict2={'x':1,'y':2}#dict3={1:x,2:y} # NameError: name 'x' is not defined,同理。dict4={1:'x',2:'y'}# 定义函数参数为字典def a(**args):    print argsa(x=1,y=2)      # 我的理解是,这里估计先要通过函数的语法检查,所以=左边必须是变量,然后才被识别为字符串'x',所以这种传递字典很局限,只能传递key为字符串的字典。#a('x'=1,'y'=2)#a(1=x,2=y)#a(1='x',2='y')

如果要传递任意的字典,不如这样:

[python]
  1. def a(dict)  
  2. dict={
    1:'x',2='y'}  
  3. a(dict)  
def a(dict)dict={1:'x',2='y'}a(dict)

【字符串相关】

1 格式化输出:

[python]
  1. format="%s%d" % (str1,num)  
  2. print format  
format="%s%d" % (str1,num)print format
2 用+进行字符串的合并:
[python]
  1. str1="hello"  
  2. str2="world"  
  3. result=str1+str2  
str1="hello"str2="world"result=str1+str2
3 字符串截取可以通过索引/切片,也可以通过split函数。
4 通过切片截取字符串:
[python]
  1. word="world"  
  2. print word[0:3]  
word="world"print word[0:3]
5 python使用==和!=来进行字符串比较。如果比较的两个变量的类型不相同,那么结果必然为不同。

[python]
  1. # -* - coding: UTF-8 -* -   
  2. #!/usr/bin/python   
  3. # Filename: str_methods.py   
  4.   
  5. # 字符串name   
  6. name = 'Swaroop'   
  7.   
  8. # name.startswith("") startwith方法是用来测试字符串是否以给定字符串开始   
  9. if name.startswith('Swa'):  
  10.     print 'Yes, the string starts with "Swa"'  
  11. # in                  in操作符用来检验一个给定字符串是否为另一个字符串的一部分   
  12. if 'a' in name:  
  13.     print 'Yes, it contains the string "a"'  
  14. # name.find("")       find方法用来找出给定字符串在另一个字符串中的位置,或者返回-1以表示找不到子字符串   
  15. if name.find('war') != -1:  
  16.     print 'Yes, it contains the string "war"'  
  17. #                     str类也有以一个作为分隔符的字符串join序列的项目的整洁的方法,它返回一个生成的大字符串   
  18. delimiter = '_*_'  
  19. mylist = ['Brazil''Russia''India''China']  
  20. print delimiter.join(mylist)  
# -* - coding: UTF-8 -* -#!/usr/bin/python# Filename: str_methods.py# 字符串namename = 'Swaroop' # name.startswith("") startwith方法是用来测试字符串是否以给定字符串开始if name.startswith('Swa'):    print 'Yes, the string starts with "Swa"'# in                  in操作符用来检验一个给定字符串是否为另一个字符串的一部分if 'a' in name:    print 'Yes, it contains the string "a"'# name.find("")       find方法用来找出给定字符串在另一个字符串中的位置,或者返回-1以表示找不到子字符串if name.find('war') != -1:    print 'Yes, it contains the string "war"'#                     str类也有以一个作为分隔符的字符串join序列的项目的整洁的方法,它返回一个生成的大字符串delimiter = '_*_'mylist = ['Brazil', 'Russia', 'India', 'China']print delimiter.join(mylist)

【文件处理】

1,读写文件

 读取文件可以使用readline()函数、readlines()函数和read函数。

    写入文件可以使用write()、writelines()函数

[python]
  1. # -* - coding: UTF-8 -* -   
  2. #!/usr/bin/python   
  3. # Filename: using_file.py   
  4.   
  5. poem = '''''\ 
  6. Programming is fun 
  7. When the work is done 
  8. if you wanna make your work also fun: 
  9.         use Python! 
  10. '''  
  11.   
  12. # 以写模式打开文件,模式可以为读模式('r')、写模式('w')或追加模式('a')   
  13. f = file('poem.txt''w')  
  14. # 写入内容   
  15. f.write(poem)   
  16. # 关闭文件    
  17. f.close()   
  18.   
  19. # 以读模式打开文件,不指定mode默认为读   
  20. f = file('poem.txt')  
  21. # 逐行读取内容   
  22. while True:  
  23.     line = f.readline()  
  24.     if len(line) == 0# 长度为0表示读到EOF   
  25.         break  
  26.     print line,  
  27.     # 注意逗号表示避免换行   
  28. # 关闭文件   
  29. f.close()   
# -* - coding: UTF-8 -* -#!/usr/bin/python# Filename: using_file.pypoem = '''\Programming is funWhen the work is doneif you wanna make your work also fun:        use Python!'''# 以写模式打开文件,模式可以为读模式('r')、写模式('w')或追加模式('a')f = file('poem.txt', 'w')# 写入内容f.write(poem) # 关闭文件 f.close() # 以读模式打开文件,不指定mode默认为读f = file('poem.txt')# 逐行读取内容while True:    line = f.readline()    if len(line) == 0: # 长度为0表示读到EOF        break    print line,    # 注意逗号表示避免换行# 关闭文件f.close()

2,我的常用格式

[python]
  1. read_file = open("new_tablelist.txt").read()  
  2. write_file = open("a.txt","w")  
  3. for words in read_file.split("\n"):  
  4.     if words != "":  
  5.         write_file.write(words.split(":")[1]+"\n")  
  6. write_file.close()  
read_file = open("new_tablelist.txt").read()write_file = open("a.txt","w")for words in read_file.split("\n"):    if words != "":        write_file.write(words.split(":")[1]+"\n")write_file.close()

3 读写对象【存储器】

Python提供一个标准的模块,称为pickle。使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为 持久地 储存对象。

还有另一个模块称为cPickle,它的功能和pickle模块完全相同,只不过它是用C语言编写的,因此要快得多(比pickle快1000倍)。你可以使用它们中的任一个,而我们在这里将使用cPickle模块。记住,我们把这两个模块都简称为pickle模块。

[python]
  1. # -* - coding: UTF-8 -* -   
  2. #!/usr/bin/python   
  3. # Filename: pickling.py   
  4.   
  5. import cPickle as p  
  6. #import pickle as p   
  7.   
  8. # 建立两个对象   
  9. shoplistfile = 'shoplist.data'  
  10. shoplist = ['apple''mango''carrot']  
  11.   
  12. # 将对象写入文件   
  13. f = file(shoplistfile, 'w')  
  14. p.dump(shoplist, f)   
  15. f.close()  
  16.   
  17. # 删除对象   
  18. del shoplist  
  19.   
  20. # 从文件中读取对象   
  21. f = file(shoplistfile)  
  22. storedlist = p.load(f)  
  23. print storedlist  
# -* - coding: UTF-8 -* -#!/usr/bin/python# Filename: pickling.pyimport cPickle as p#import pickle as p# 建立两个对象shoplistfile = 'shoplist.data'shoplist = ['apple', 'mango', 'carrot']# 将对象写入文件f = file(shoplistfile, 'w')p.dump(shoplist, f) f.close()# 删除对象del shoplist# 从文件中读取对象f = file(shoplistfile)storedlist = p.load(f)print storedlist

【对象和类】

1 python用class保留字来定义一个类,
类名的首字符要大写。定义类示例:
[python]
  1. class Fruit:  
  2.     def grow(self):  
  3.        print "Fruit grow"  
class Fruit:    def grow(self):       print "Fruit grow"

类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称,但是在调用这个方法的时候你不为这个参数赋值,Python会提供这个值。这个特别的变量指对象本身,按照惯例它的名称是self。

Python中的self等价于C++中的self指针和Java、C#中的this参考。
假如你有一个类称为MyClass和这个类的一个实例MyObject。当你调用这个对象的方法MyObject.method(arg1, arg2)的时候,这会由Python自动转为MyClass.method(MyObject, arg1, arg2)——这就是self的原理了。

2 当一个对象被创建后,包含了三方面的特性,即对象的句柄、属性和方法。创建对象的方法:

[python]
  1. fruit = Fruit()  
  2. fruit.grow()  
fruit = Fruit()fruit.grow()

3 python没有保护类型的修饰符

4 类的方法也分为公有方法和私有方法。私有函数不能被该类之外的函数调用,私有的方法也不能被外部的类或函数调用。
5 python使用函数”staticmethod()“或”@ staticmethod“指令的方法把普通的函数转换为静态方法。静态方法相当于全局函数。

6 python的构造函数名为__init__,析构函数名为__del__

[python]
  1. # -* - coding: UTF-8 -* -   
  2. #!/usr/bin/python   
  3. # Filename: objvar.py   
  4.   
  5. class Person:  
  6.     '''''Represents a person.'''  
  7.     # 这是类的变量   
  8.     population = 0  
  9.   
  10.     # 构造函数   
  11.     def __init__(self, name):  
  12.         '''''Initializes the person's data.'''  #类的文档字符串   
  13.         # 这里是self.name,所以这个name是对象的变量   
  14.         self.name = name  
  15.         print '(Initializing %s)' % self.name  
  16.         # 构造函数使得类的变量population+1   
  17.         Person.population += 1  
  18.   
  19.     # 析构函数   
  20.     def __del__(self):  
  21.         '''''I am dying.'''  #方法的文档字符串   
  22.         print '%s says bye.' % self.name  
  23.         Person.population -= 1  
  24.   
  25.         if Person.population == 0:  
  26.             print 'I am the last one.'  
  27.         else:  
  28.             print 'There are still %d people left.' % Person.population  
  29.   
  30.     def sayHi(self):  
  31.         '''''Greeting by the person. 
  32.  
  33.         Really, that's all it does.'''  
  34.         print 'Hi, my name is %s.' % self.name  
  35.   
  36.     def howMany(self):#如果这个函数要调用本类的sayHi(self),需要操作self.sayHi()   
  37.         '''''Prints the current population.'''  
  38.         if Person.population == 1:  
  39.             print 'I am the only person here.'  
  40.         else:  
  41.             print 'We have %d persons here.' % Person.population  
  42.   
  43. # 我们可以在运行时使用Person.__doc__和Person.sayHi.__doc__来分别访问类与方法的文档字符串。   
  44. swaroop = Person('Swaroop')  
  45. swaroop.sayHi()  
  46. swaroop.howMany()  
  47.   
  48. kalam = Person('Abdul Kalam')  
  49. kalam.sayHi()  
  50. kalam.howMany()  
  51.   
  52. swaroop.sayHi()  
  53. swaroop.howMany()  
# -* - coding: UTF-8 -* -#!/usr/bin/python# Filename: objvar.pyclass Person:    '''Represents a person.'''    # 这是类的变量    population = 0    # 构造函数    def __init__(self, name):        '''Initializes the person's data.'''  #类的文档字符串        # 这里是self.name,所以这个name是对象的变量        self.name = name        print '(Initializing %s)' % self.name        # 构造函数使得类的变量population+1        Person.population += 1    # 析构函数    def __del__(self):        '''I am dying.'''  #方法的文档字符串        print '%s says bye.' % self.name        Person.population -= 1        if Person.population == 0:            print 'I am the last one.'        else:            print 'There are still %d people left.' % Person.population    def sayHi(self):        '''Greeting by the person.        Really, that's all it does.'''        print 'Hi, my name is %s.' % self.name    def howMany(self):#如果这个函数要调用本类的sayHi(self),需要操作self.sayHi()        '''Prints the current population.'''        if Person.population == 1:            print 'I am the only person here.'        else:            print 'We have %d persons here.' % Person.population# 我们可以在运行时使用Person.__doc__和Person.sayHi.__doc__来分别访问类与方法的文档字符串。swaroop = Person('Swaroop')swaroop.sayHi()swaroop.howMany()kalam = Person('Abdul Kalam')kalam.sayHi()kalam.howMany()swaroop.sayHi()swaroop.howMany()

7 继承的使用方法:
[python]
  1. class Apple(Fruit):  
  2.    def …  
class Apple(Fruit):   def …

[python]
  1. # -* - coding: UTF-8 -* -   
  2. #!/usr/bin/python   
  3. # Filename: inherit.py   
  4.   
  5. class SchoolMember:  
  6.     '''''Represents any school member.'''  
  7.     def __init__(self, name, age):  
  8.         self.name = name  
  9.         self.age = age  
  10.         print '(Initialized SchoolMember: %s)' % self.name  
  11.   
  12.     def tell(self):  
  13.         '''''Tell my details.'''  
  14.         print 'Name:"%s" Age:"%s"' % (self.name, self.age),  
  15.   
  16. class Teacher(SchoolMember):  
  17.     '''''Represents a teacher.'''  
  18.     def __init__(self, name, age, salary):  
  19.         SchoolMember.__init__(self, name, age)  
  20.         self.salary = salary  
  21.         print '(Initialized Teacher: %s)' % self.name  
  22.   
  23.     def tell(self):  
  24.         SchoolMember.tell(self)  
  25.         print 'Salary: "%d"' % self.salary  
  26.   
  27. class Student(SchoolMember):  
  28.     '''''Represents a student.'''  
  29.     def __init__(self, name, age, marks):  
  30.         SchoolMember.__init__(self, name, age)  
  31.         self.marks = marks  
  32.         print '(Initialized Student: %s)' % self.name  
  33.   
  34.     def tell(self):  
  35.         SchoolMember.tell(self)  
  36.         print 'Marks: "%d"' % self.marks  
  37.   
  38. t = Teacher('Mrs. Shrividya'4030000)  
  39. s = Student('Swaroop'2275)  
  40.   
  41. print # prints a blank line   
  42.   
  43. members = [t, s]  
  44. for member in members:  
  45.     member.tell() # works for both Teachers and Students  
# -* - coding: UTF-8 -* -#!/usr/bin/python# Filename: inherit.pyclass SchoolMember:    '''Represents any school member.'''    def __init__(self, name, age):        self.name = name        self.age = age        print '(Initialized SchoolMember: %s)' % self.name    def tell(self):        '''Tell my details.'''        print 'Name:"%s" Age:"%s"' % (self.name, self.age),class Teacher(SchoolMember):    '''Represents a teacher.'''    def __init__(self, name, age, salary):        SchoolMember.__init__(self, name, age)        self.salary = salary        print '(Initialized Teacher: %s)' % self.name    def tell(self):        SchoolMember.tell(self)        print 'Salary: "%d"' % self.salaryclass Student(SchoolMember):    '''Represents a student.'''    def __init__(self, name, age, marks):        SchoolMember.__init__(self, name, age)        self.marks = marks        print '(Initialized Student: %s)' % self.name    def tell(self):        SchoolMember.tell(self)        print 'Marks: "%d"' % self.markst = Teacher('Mrs. Shrividya', 40, 30000)s = Student('Swaroop', 22, 75)print # prints a blank linemembers = [t, s]for member in members:    member.tell() # works for both Teachers and Students

8 对象的深度拷贝

要想取得深层拷贝,必须使用切片操作符来获取整个拷贝。

[python]
  1. # -* - coding: UTF-8 -* -   
  2. #!/usr/bin/python   
  3. # Filename: reference.py   
  4.   
  5. # mylist和shoplist都只想同一个内存对象。   
  6. shoplist = ['apple''mango''carrot''banana']  
  7. mylist = shoplist   
  8.   
  9. # mylist和shoplist都少了apple   
  10. del shoplist[0]  
  11.   
  12. # 这才是深层复制,mylist和shoplist对应两个不同的对象了。   
  13. mylist = shoplist[:]   
  14.   
  15. # 这里只删除了mylist的第一个单词   
  16. del mylist[0]   
# -* - coding: UTF-8 -* -#!/usr/bin/python# Filename: reference.py# mylist和shoplist都只想同一个内存对象。shoplist = ['apple', 'mango', 'carrot', 'banana']mylist = shoplist # mylist和shoplist都少了appledel shoplist[0]# 这才是深层复制,mylist和shoplist对应两个不同的对象了。mylist = shoplist[:] # 这里只删除了mylist的第一个单词del mylist[0]

【异常处理】

1,使用try except语句

直接在python cmd里这样测试,尝试读取用户的一段输入。按Ctrl-d,看一下会发生什么:

[python]
  1. >>> s = raw_input('Enter something --> ')  
  2. Enter something -->   
  3.   
  4. Traceback (most recent call last):  
  5.   File "<pyshell#0>", line 1in <module>  
  6.     s = raw_input('Enter something --> ')  
  7. EOFError: EOF when reading a line  
>>> s = raw_input('Enter something --> ')Enter something --> Traceback (most recent call last):  File "
", line 1, in
s = raw_input('Enter something --> ')EOFError: EOF when reading a line
我们可以使用try..except语句来处理异常。我们把通常的语句放在try-块中,而把我们的错误处理语句放在except-块中

[python]
  1. # -* - coding: UTF-8 -* -   
  2. #!/usr/bin/python   
  3. # Filename: try_except.py   
  4.   
  5. import sys  
  6.   
  7. try:  
  8.     s = raw_input('Enter something --> ')  
  9. except EOFError as err:  
  10.     print '\nWhy did you do an EOF on me?'+str(err)  
  11.     sys.exit # 直接退出   
  12. except:  
  13.     print '\nSome error/exception occurred.'  
  14. print 'Done'  
# -* - coding: UTF-8 -* -#!/usr/bin/python# Filename: try_except.pyimport systry:    s = raw_input('Enter something --> ')except EOFError as err:    print '\nWhy did you do an EOF on me?'+str(err)    sys.exit # 直接退出except:    print '\nSome error/exception occurred.'print 'Done'

2,自己构造异常类

[python]
  1. # -* - coding: UTF-8 -* -   
  2. #!/usr/bin/python   
  3. # Filename: raising.py   
  4.   
  5. # 定义一个异常类ShortInputException,该类继承自Exception   
  6. class ShortInputException(Exception):  
  7.     '''''A user-defined exception class.'''  
  8.     def __init__(self, length, atleast):#self是必须的,length表示当前输入长度,atleast表示应输入长度   
  9.         Exception.__init__(self)  
  10.         self.length = length    # 对象的私有变量   
  11.         self.atleast = atleast  # 对象的私有变量   
  12.    
  13. try:  
  14.     s = raw_input('Enter something --> ')  
  15.     if len(s) < 3:  
  16.         raise ShortInputException(len(s), 3# 主动抛出异常   
  17. except EOFError:  
  18.     print '\nWhy did you do an EOF on me?'  
  19. except ShortInputException, x:  
  20.     print 'ShortInputException: The input was of length %d, was expecting at least %d' % (x.length, x.atleast)  
  21. else:  
  22.     print 'No exception was raised.'  
# -* - coding: UTF-8 -* -#!/usr/bin/python# Filename: raising.py# 定义一个异常类ShortInputException,该类继承自Exceptionclass ShortInputException(Exception):    '''A user-defined exception class.'''    def __init__(self, length, atleast):#self是必须的,length表示当前输入长度,atleast表示应输入长度        Exception.__init__(self)        self.length = length    # 对象的私有变量        self.atleast = atleast  # 对象的私有变量 try:    s = raw_input('Enter something --> ')    if len(s) < 3:        raise ShortInputException(len(s), 3) # 主动抛出异常except EOFError:    print '\nWhy did you do an EOF on me?'except ShortInputException, x:    print 'ShortInputException: The input was of length %d, was expecting at least %d' % (x.length, x.atleast)else:    print 'No exception was raised.'
测试结果:

[python]
  1. >>> ================================ RESTART ================================  
  2. >>>   
  3. Enter something -->   
  4.   
  5. Why did you do an EOF on me?  
  6. >>> ================================ RESTART ================================  
  7. >>>   
  8. Enter something --> ab  
  9. ShortInputException: The input was of length 2, was expecting at least 3  
  10. >>> ================================ RESTART ================================  
  11. >>>   
  12. Enter something --> abc  
  13. No exception was raised.  
  14. >>>   
>>> ================================ RESTART ================================>>> Enter something --> Why did you do an EOF on me?>>> ================================ RESTART ================================>>> Enter something --> abShortInputException: The input was of length 2, was expecting at least 3>>> ================================ RESTART ================================>>> Enter something --> abcNo exception was raised.>>>

3,使用try finally

[python]
  1. # -* - coding: UTF-8 -* -   
  2. #!/usr/bin/python   
  3. # Filename: finally.py   
  4.   
  5. import time  
  6.   
  7. try:  
  8.     f = file('poem.txt')  
  9.     while True:  
  10.         line = f.readline()  
  11.         if len(line) == 0:# len(line)==0表示读到文件EOF   
  12.             break  
  13.         time.sleep(2)  
  14.         print line,  
  15. finally:  
  16.     f.close()  
  17.     print 'Cleaning up...closed the file'  
# -* - coding: UTF-8 -* -#!/usr/bin/python# Filename: finally.pyimport timetry:    f = file('poem.txt')    while True:        line = f.readline()        if len(line) == 0:# len(line)==0表示读到文件EOF            break        time.sleep(2)        print line,finally:    f.close()    print 'Cleaning up...closed the file'
我们进行通常的读文件工作,但是我有意在每打印一行之前用time.sleep方法暂停2秒钟。这样做的原因是让程序运行得慢一些(Python由于其本质通常运行得很快)。在程序运行的时候,按Ctrl-c中断/取消程序。
我们可以观察到KeyboardInterrupt异常被触发,程序退出。但是在程序退出之前,finally从句仍然被执行,把文件关闭。

4,使用with来避免finally

with可以用来简化try finally代码,看起来可以比try finally更清晰。

例如打开文件操作:

[python]
  1. try:  
  2.     f = open('a.txt')  
  3.     print f.readlines()   
  4. finally:  
  5.     f.close()  
try:	f = open('a.txt')	print f.readlines() finally:	f.close()

如果使用with,则明显提高友好度:

[python]
  1. with open('a.txt') as f:    
  2.     print f.readlines()   
with open('a.txt') as f:      print f.readlines()
为了我们自己的类也可以使用with, 只要给这个类增加两个函数__enter__, __exit__即可:

[python]
  1. >>> class A:  
  2.     def __enter__(self):  
  3.         print 'in enter'  
  4.     def __exit__(self, e_t, e_v, t_b):  
  5.         print 'in exit'  
  6.   
  7. >>> with A() as a:  
  8.     print 'in with'  
  9.   
  10. in enter  
  11. in with  
  12. in exit  
>>> class A:	def __enter__(self):		print 'in enter'	def __exit__(self, e_t, e_v, t_b):		print 'in exit'>>> with A() as a:	print 'in with'in enterin within exit

【连接mysql】

1 用MySQLdb模块操作MySQL数据库非常方便。示例代码如下:
[python]
  1. import os, sys  
  2. import MySQLdb  
  3. try:  
  4.     conn MySQLdb.connect(host=’localhost’,user=’root’,passwd=’’,db=’address’  
  5. except Exception,e:  
  6.     print e  
  7.     sys.exit()  
  8. cursor=conn.cursor()  
  9. sql=’insert into address(name, address) values(%s, %s)’  
  10. value=((“zhangsan”,”haidian”),(“lisi”,”haidian”))  
  11. try  
  12.     cursor.executemany(sql,values)  
  13. except Exception, e:  
  14.     print e  
  15. sql=”select * from address”  
  16. cursor.execute(sql)  
  17. data=cursor.fetchall()  
  18. if data  
  19.     for x in data:  
  20.         print x[0],x[1]  
  21. cursor.close()  
  22. conn.close()  
import os, sysimport MySQLdbtry:    conn MySQLdb.connect(host=’localhost’,user=’root’,passwd=’’,db=’address’except Exception,e:    print e    sys.exit()cursor=conn.cursor()sql=’insert into address(name, address) values(%s, %s)’value=((“zhangsan”,”haidian”),(“lisi”,”haidian”))try    cursor.executemany(sql,values)except Exception, e:    print esql=”select * from address”cursor.execute(sql)data=cursor.fetchall()if data    for x in data:        print x[0],x[1]cursor.close()conn.close()

【多线程】

python[cpython] 的GIL规定每个时刻只能有一个线程访问python虚拟机,所以你要用python的多线程来做计算是很不合算的,但是对于IO密集型的应用,例如网络交互来说,python的多线程还是非常给力的。如果你是一个计算密集型的任务,非要用python来并行执行的话,有以下几个方法:

1 使用python的multiprocessing 模块,能够发挥多核的优势。
2 使用ironPython,但是这个只能在windows下用
3 使用pypy,这个可以实现真正的多线程。

【easy_install工具】

Python中的easy_install工具很爽,它的作用类似于Php中的pear,或者Ruby中的gem,或者Perl中的cpan。

[plain]
  1. wget -q http://peak.telecommunity.com/dist/ez_setup.py  
  2. python ez_setup.py  
wget -q http://peak.telecommunity.com/dist/ez_setup.pypython ez_setup.py

有时候可能需要再安装python-dev

[plain]
  1. sudo yum install python-devel  
sudo yum install python-devel

例如安装python的代码覆盖率工具:

[plain]
  1. sudo easy_install coverage  
sudo easy_install coverage

转载地址:https://blog.csdn.net/u013494310/article/details/20617959 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:多线程精华,面试专用
下一篇:大家一起去东莞!!

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年04月04日 06时02分33秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章