1、条件语句spa
一、布尔值code
条件语句中,判断条件的值通常是布尔值。即条件为真时,将执行什么,条件为假时,将执行什么。对象
下面的值在做为布尔表达式的时候,会被解释器看作假(false):blog
False None 0 "" () [] {}input
注:虽然上面的值被看作是假,可是它们自己并不相等,也就是说None != ()it
二、条件语句io
a、if语句for循环
b、if....else语句class
c、if....elif...elif...else语句exception
num = input('Enter a number:') if num>0: print 'the number is positive' elif num<0: print 'the number is negative' else: print 'the number is zero'
d、嵌套代码块,if....else语句中,if代码块中还包含if...else语句之类
2、循环
一、while循环
x = 1 while x <= 5: print x x += 1
二、for循环
for i in range(4): print(i)
3、跳出循环
通常状况下,循环会一直执行到条件为假,或者到序列元素用完时。可是有些时候可能会提早中断一个循环,进行新的迭代,或者仅仅就是想结束循环
一、break
二、continue
三、while True/break习语
while true: word = raw_input('please enter a word:') if not word:break print 'the word was '+ words
4、列表推导式
是利用其它列表建立新列表的一种方法。
print([x*x for x in range(5)]) #[0, 1, 4, 9, 16]
5、异常
一、raise语句,用来引起异常
raise Exception('something is wrong')
二、try..except语句,捕捉异常
三、try..except...except,不止一个except子句
四、try...except () as e,捕捉对象,记录下错误
五、try...except..else..,若是没有发生异常,执行完try子句后,会执行else子句;
try: print 'the right way' except Exception as e: print 'the wrong way' print 'return the exception:',e else: print 'continue the right way'
finally:
print 'all continue'
六、try...except..finally..无论异常是否发生,都会执行finally子句;