for 循环和range()内建函数
>>> for item in ['e-mail', 'net-surfing', 'homework',
... 'chat']:
... print item
...
e-mail
net-surfing
homework
chat
... 'chat']:
... print item
...
net-surfing
homework
chat
>>> for item in ['e-mail', 'net-surfing', 'homework',
... 'chat']:
... print item ,
...
e-mail net-surfing homework chat
... 'chat']:
... print item ,
...
e-mail net-surfing homework chat
>>> s='23f4'
>>> for i in s:
... print i
...
2
3
f
4
... print i
...
2
3
f
4
>>> for i in range(len(s)):
... print s[i],'(%d)' % i
...
2 (0)
3 (1)
f (2)
4 (3)
... print s[i],'(%d)' % i
...
2 (0)
3 (1)
f (2)
4 (3)
>>> for i, ch in enumerate(s):
... print ch, '(%d)' % i
...
2 (0)
3 (1)
f (2)
4 (3)
... print ch, '(%d)' % i
...
2 (0)
3 (1)
f (2)
4 (3)
列表解析
>>> squared = [x ** 2 for x in range(4)]
>>> for i in squared:
... print i
...
0
1
4
9
>>> for i in squared:
... print i
...
0
1
4
9
文件和内建函数open() 、file()
handle = open(file_name, access_mode = 'r')
'r'(default)
‘w'
’a'
‘+’
‘b'
句点属性标识法访问
file=raw_input('enter file name:')
c=open(file,'r')
for eachline in c:
print eachline,
c.close()
c=open(file,'r')
for eachline in c:
print eachline,
c.close()
我们一次读入文件的所有行,然后关闭文件, 再迭代每一行输出。这样写代码的好处是能够快速完整的访问文件。
对于很大的文件来说, 上面的代码会占用太多的内存, 这时最好一次读一行。
错误和异常 try-except
try之后的代码组, 就是你打算管理的代码。 except 之后的代码组, 则是你处理错误的代码。
#!/usr/bin/python
try:
file=raw_input('enter file name:')
c=open(file,'r')
for eachline in c:
print eachline,
c.close()
except IOError, e:
print 'file open error',e
try:
file=raw_input('enter file name:')
c=open(file,'r')
for eachline in c:
print eachline,
c.close()
except IOError, e:
print 'file open error',e
enter file name:2.txt
file open error [Errno 2] No such file or directory: '2.txt'
函数
def function_name([arguments]):
"optional documentation string"
function_suite
"optional documentation string"
function_suite
#vim b.py
def addw(x):
'apply + operation to argument'
return (x+x)
'apply + operation to argument'
return (x+x)
>>> import b
>>> from b import addw
>>> addw(3)
6
>>> addw(3)
6
>>> addw([-1,'as'])
[-1, 'as', -1, 'as']
[-1, 'as', -1, 'as']
默认参数
类
class ClassName(base_class[es]):
"optional documentation string"
static_member_declarations
method_declarations
"optional documentation string"
static_member_declarations
method_declarations
class Foo(object):
"""jksdja"""
version=0.1
def __init__(self,nm='li'):
"""constructor"""
self.name=nm
print 'create',nm
def showname(self):
"""display instance attribute and class name"""
print 'My name is', self.__class__.__name__
def showver(self):
"""display class(static) attribute"""
print self.version # references FooClass.version
def addMe2Me(self, x): # does not use 'self'
"""apply + operation to argument"""
return x + x
"""jksdja"""
version=0.1
def __init__(self,nm='li'):
"""constructor"""
self.name=nm
print 'create',nm
def showname(self):
"""display instance attribute and class name"""
print 'My name is', self.__class__.__name__
def showver(self):
"""display class(static) attribute"""
print self.version # references FooClass.version
def addMe2Me(self, x): # does not use 'self'
"""apply + operation to argument"""
return x + x
>>> import c
>>> from c import Foo
>>> foo=Foo()
create li
create li
>>> foo.showname()
My name is Foo
My name is Foo
模块
import module_name
>>> import sys
>>> sys.stdout.write('hello')
hello>>> sys.platform
'linux2'
>>> sys.version
'2.4.3 (#1, Jan 9 2013, 06:47:03) \n[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)]'
>>> sys.stdout.write('hello')
hello>>> sys.platform
'linux2'
>>> sys.version
'2.4.3 (#1, Jan 9 2013, 06:47:03) \n[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)]'
实用函数
dir([obj]) 显示对象的属性,如果没有提供参数, 则显示全局变量的名字
int(obj) 将一个对象转换为整数
len(obj) 返回对象的长度
raw_input(str) 等待用户输入一个字符串, 可以提供一个可选的参数 str 用作提示信息。
str(obj) 将一个对象转换为字符串
type(obj) 返回对象的类型(返回值本身是一个type 对象!)
type(obj) 返回对象的类型(返回值本身是一个type 对象!)