1、if语句的格式 if test1: statement1 elif test2: statement2 else statement3 2、在python中没有switch/case语句,可以通过字典或者if,elif,else模拟 例如: choice = 'ham' print({'spam':1.25,'ham':1.99,'eggs':0.99,'bacon':1.10}[choice]) 或者: if choice == 'spam': print(1.25) elif choice == 'ham': print(1.99) elif choice == 'eggs': print(0.99) elif choice == 'bacon': print(1.10) else : print('bad choice') 如果有默认处理情况,则通过字典的get方法 例如: branch = {'spam':1.25,'ham':1.99,'eggs':0.99,'bacon':1.10} print(branch.get('spam','bad choice')) 3、跨越多行的方法:()|{}|[]或者(不提倡使用)或者''' ''' """ """ 4、任何非零数字或者非空对象都为真,数字零,空对象,特殊对象,None都被认作是假,比较和相等测试会递归应用在数据结构中 5、or操作,python会由左到右求算操作对象,返回第一个为真的对象,如果没有为真的对象,则返回最后一个对象。 print((2 or 3), (3 or 2)) #输出:2,3 print([] or 3) #输出:3 print([] or {}) #输出:{} 6、and操作,python会由左向右求算操作对象,当所有的为真时,返回右边那个对象,如果遇到为假的对象,则返回第一个为假的对象 print((2 and 3), (3 and 2)) #输出:3,2 print([] and 3) #输出:[] print([] and {}) #输出:[] 7、if/else三元表达式 if x: a = y else: a = z 等价于: a = y if x else z 等价于: a = ((x and y) or z) 等价于: a = ('z','y')[bool(x)] 8、while循环,当没有执行break语句时,才执行else部分 while test: statement1 else statement2 9、在python中有一条空语句:pass 它什么也不做 10、for循环 for target in object : statement else statement 例如: D = {'a':1,'b':2,'c':3} for key in D: print(key,'=>',D[key]) for (key,value) in D.items(): print(key,'=>',value) 11、range用法,range(终止),range(起始,终止),range(起始,终止,步长 )起始默认是0,步长默认是1 12、在python2.6中map也能实现zip函数功能,但是在python3.0中不能使用 例如: map(None,('a',b','c'),(1,2,3)) #输出:[('a':1,'b':2,'c':3)] 13、enumerate返回索引和该索引位置上所对应的值,该函数对字符串,列表,元组有效,对字典没有效 例如: s = 'spam' for (i,v) in enumerate(s): print(i,'->',v) print('*'*8) L = ['a','b','c','d'] for (i,v) in enumerate(L): print(i,'->',v) print('*'*8) t = ('a','b','c','d') for (i,v) in enumerate(t): print(i,'->',v) print('*'*8)