while_else, for_else 以及try_exception_else_finally
Posted zmiao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了while_else, for_else 以及try_exception_else_finally相关的知识,希望对你有一定的参考价值。
在python中的while, for和try是有else分支的. 关于while的else分支描述如下
The while statement is used for repeated execution as long as an expression is true: while_stmt ::= "while" expression ":" suite ["else" ":" suite] This repeatedly tests the expression and, if it is true, executes the first suite; if
the expression is false (which may be the first time it is tested) the suite of the else
clause, if present, is executed and the loop terminates. A break statement executed in the first suite terminates the loop without executing the
else clause’s suite. A continue statement executed in the first suite skips the rest of
the suite and goes back to testing the expression.
总结一句话就是当while或者for正常结束循环,那么else分支就会被执行.即当expression条件不再满足,
如果在执行循环过程中由于break, return等退出,那么else分支不被执行.
对于try... exception...else 当try分支执行后没有产生exception,那么执行else分支.如果有finally分支,则
无论有没有exception,最后都会执行finally分支.但是前提是finally得有except X/except处理了exception,finally
才会被执行. 例子如下: file_bname是一个bytes类型的文件名字, file_name是字符串形式的
(1)当没有出现except时,else和finally被执行
>>> try: ... file_bname.decode(‘gb2312‘) ... except TypeError: ... print(‘hello‘) ... else: ... print(‘else‘) ... finally: ... print(‘finally‘) ... ‘迈瑞医疗(300760)_利润表.xls‘ else finally
(2)当有except的时候,else没有被执行, finally被执行
>>> file_name.decode(‘gb2312‘) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: ‘str‘ object has no attribute ‘decode‘ >>> try: ... file_name.decode(‘gb2312‘) ... except AttributeError: ... print(‘Error‘) ... else: ... print(‘else‘) ... finally: ... print(‘finally‘) ... Error finally
(3)else前面必须跟着except X或者except
>>> try: ... file_name.decode(‘gb2312‘) ... else: File "<stdin>", line 3 else: ^ SyntaxError: invalid syntax
(4) 如果except没有得到处理,即使有finally,也没有被执行
>>> try: ... file_name.decode(‘gb2312‘) ... finally: ... print(‘finally‘) ... finally Traceback (most recent call last): File "<stdin>", line 2, in <module> AttributeError: ‘str‘ object has no attribute ‘decode‘ >>>
The while statement is used for repeated execution as long as an expression is true:
while_stmt ::= "while" expression ":" suite
["else" ":" suite]
This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else
clause, if present, is executed and the loop terminates.
A break
statement executed in the first suite terminates the loop without executing the else
clause’s suite. A continue
statement executed in the first suite skips the rest of the suite and goes back to testing the expression.
以上是关于while_else, for_else 以及try_exception_else_finally的主要内容,如果未能解决你的问题,请参考以下文章
dl以及dt,dd,以及table的tr,th,td最清楚分析