13. Hello world (1) 表达式 2 + 3 3 + (7 * 4) 3 ** 5 ‘Hello’ + ‘World’ 变量赋值 a = 4 << 3 b = a * 4.5 c = (a+b)/2.5 a = “Hello World” x,y = 4+2,”python” pass 语句– 不做任何事时使用 if a < b: pass else: c = a
14. Hello world (2) if…elif…else语句: 没有switch,有更高级的变通方式(dict字典方式) if a == ‘+’: b = ‘+’ elif a == ‘-’: b = ‘-’ else: b = None 布尔表达式– and, or, not if b >= a and b <= c: print ‘bool is True’ if not (b < a or c > c): print ‘not expr, value is True’
18. 列表list 赋值 a = [2, 3, 4] # A list of integer b = [2, 7, 3.5, “Hello”] # A mixed list c = [] # An empty list d = [2, [a, b]] # 嵌套列表 e = a + b # Join two lists 操作 x = a[1] # Get 2nd element (0 is first) y = b[1:3] # Return a sub-list z = d[1][0][2] # Nested lists b[0] = 42 # Change an element print sum(a) # = 9 x = a.pop(0) # pop第一个数据
19. tuple 赋值 f = (2,3,4,5) # A tuple of integers g = (,) # An empty tuple h = (2, [3,4], (10,11,12))# A tuple containing mixed objects 操作 x = f[1] # Element access. x = 3 y = f[1:3] # Slices. y = (3,4) z = h[1][1] # Nesting. z = 4 特色 与list类似,最大的不同tuple是一种只读且不可变更的数据结构 不可取代tuple中的任意一个元素,因为它是只读不可变更的,也不能进行像list一样的加法操作
20. 字典dict 赋值 a = { } # An empty dictionary b = { ’x’: 3, ’y’: 4 }#有点类似json格式 c = { ’uid’: 105, ’login’: ’beazley’, ’name’ : ’David Beazley’ } 操作 u = c[’uid’] # Get an element c[’shell’] = "/bin/sh" # Set an element dict2 = dict2.update(dict1) #使用dict1中的数据去更新dict2 if c.has_key("directory"): # Check for presence of an member d = c[’directory’] else: d = None d = c.get(“directory”,None) # 带默认值的方式
22. 循环 While语句 while a < b: a = a + 1 break For语句(遍历序列的元素) for item in [3, 4, 10, 25]: print item # Print characters one at a time for c in "Hello World": print c # Loop over a range of numbers for i in xrange(0,100,2): print i for i in xrange(len(list1)): print list1[i]
24. 函数 def语句 def func1(a,b):#没有指针,函数内的数据只能通过返回 q = a/b r = a - q*b return r # 调用方式 a = func1(42,5) # a = 2 返回多个值 def func2(a,b): q = a/b r = a - q*b return q,r x,y = func2(42,5) # x = 8, y = 2
25. 类class class语句 class Account: def __init__(self, initial): self.balance = initial def deposit(self, amt): self.balance = self.balance + amt def withdraw(self,amt): self.balance = self.balance – amt def getBalance(self): return self.balance 使用定义好的class a = Account(1000.0) a.deposit(550.23) a.deposit(100) a.withdraw(50) print a.getBalance()
26. 异常处理 try语句 try: f = open(“foo“,”r”) except IOError: print "Couldn’t open ’foo’. Sorry.“ raise语句 def factorial(n): if n < 0: raise ValueError,"Expected non-negative number" if (n <= 1): return 1 else: return n*factorial(n-1) 沒有处理的异常 >>> factorial(-1) Traceback (innermost last): File "<stdin>", line 1, in ? File "<stdin>", line 3, in factorial ValueError: Expected non-negative number
27. 文件操作 open()函数 f = open("foo","w") # Open a file for writing g = open("bar","r") # Open a file for reading 文件的读取/写入 f.write("Hello World") buff = g.read() # Read all data line = g.readline() # Read a single line lines = g.readlines() # Read data as a list of lines with do # py2.6以后版本提供 格式化的输入输出 使用%来格式化字符串 for i in range(0,10): f.write("2 times %d = %d" % (i, 2*i))
28. 目录操作 把path1目录下面的*.html更名为*.htm for root,dirs,files in os.walk(path1): for item in files: if item[-5:].upper() != '.HTML‘: continue filename = os.sep.join([root,item]) print filename file1 = filename[:-5]+'.htm' os.rename(filename, file1)