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 對象!)