Python 进阶 之 else块 巧(慎)用
Python 的 else 模块和其他语言的else模块相比有那么一丢丢的特殊用法,有些用法虽然不推荐用,但是别人如果用了,最起码能看懂是不是?
1:快捷返回值:
格式: value1 if expression else value1
#expression 为真,返回value1,expression为假,返回value2
>>> print 1 if 1 else 0
1
>>> print 1 if 0 else 0
0
>>>
2: if - elif - else 表达式:
格式:
if expression1: value1 elif expression2: value2 else: value3
#expression1 为真,返回value1,expression2为真,返回value2,否则返回value3
>>> if 0 == 2:
... print 2
... elif 0 == 1:
... print 1
... else:
... print 0
...
0
>>>
3:for - else 表达式:
for expression: if not loop-expression:
value1 break else: value2
#expression 为假,跳出循环,执行value2,loop-expression为假,跳出循环,执行value1
>>> for i in xrange(3): ... if i > 1: ... print "loop-expression" ... break ... else: ... print "else block" ... loop-expression >>> for i in xrange(3): ... if i > 4: ... print "loop-expression" ... break ...else: ... print "else block" ... else block
3:while - else 表达式:
与for - else 类似,不再赘述。
4:try - except - else - finally 模块
try:
expression
except:
value1
else:
value2
finally:
value3
#执行try内expression
1:执行异常,输出value1,value3
2:执行正常,输出value2,value3
>>> try: ... 1 == 1 ... except: ... print "error" ... else: ... print "else block" ... finally: ... print "finally block" ... else block finally block
>>> try: ... x == 1 ... except: ... import traceback ... print "------- except start -------" ... traceback.print_exc() ... print "------- except stop -------" ... else: ... print "else block" ... finally: ... print "finally block" ... ------- except start ------- Traceback (most recent call last): File "<stdin>", line 2, in <module> NameError: name 'x' is not defined ------- except stop ------- finally block