一, 条件语句
1, 布尔值
条件语句中, 判断条件的值一般是布尔值. 即条件为真时, 将执行什么, 条件为假时, 将执行什么.
下面的值在作为布尔表达式的时候, 会被解释器看做假 (false):
False None 0 "" () [] {}
注: 虽然上面的值被看做是假, 但是它们本身并不相等, 也就是说 None != ()
2, 条件语句
a,if 语句
b,if....else 语句
c,if....elif...elif...else 语句
- 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 语句之类
二, 循环
1,while 循环
- x = 1
- while x <= 5:
- print x
- x += 1
2,for 循环
- for i in range(4):
- print(i)
三, 跳出循环
一般情况下, 循环会一直执行到条件为假, 或者到序列元素用完时. 但是有些时候可能会提前中断一个循环, 进行新的迭代, 或者仅仅就是想结束循环
- ,break
- ,continue
3,while True/break 习语
- while true:
- Word = raw_input('please enter a word:')
- if not Word:break
- print 'the word was'+ words
四, 列表推导式
是利用其它列表创建新列表的一种方法.
print([x*x for x in range(5)]) #[0, 1, 4, 9, 16]
五, 异常
1,raise 语句, 用来引发异常
raise Exception('something is wrong')
2,try..except 语句, 捕捉异常
3,try..except...except, 不止一个 except 子句
4,try...except () as e, 捕捉对象, 记录下错误
5,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'
6,try...except..finally.. 不管异常是否发生, 都会执行 finally 子句;
来源: http://www.bubuko.com/infodetail-3037554.html