while 语句中的 try 块 [英] try block inside while statement
问题描述
我刚刚开始使用 Python 2.7,我不明白为什么会发生这样的事情:
I'm just starting out with Python 2.7 and I don't understand why something is happening:
在下面的代码中,python 2.7.2教程中的一个例子的修饰版本,我得到了一个意想不到的结果:
In the following code, an embellished version of an example from the python 2.7.2 tutorial, I get an unexpected result:
while True:
try:
x = int(raw_input("Please enter a number: "))
break
except ValueError:
print "Oops! That was not a valid number. Try again..."
else:
print 'Thanks,',x,'is indeed an integer'
finally:
print 'all done, bye'
当我输入一个整数时,代码会忽略else:
语句并直接切到finally:
.很明显,这与顶部的 while True:
有关,但为什么会发生这种情况?
When I put in an integer, the code ignores the else:
statement and cuts straight to finally:
. Clearly it's something to do with the while True:
at the top but why is it happening?
推荐答案
break 语句正在退出循环,因此永远不会到达 else 语句.
The break statement is pulling out of the loop, so the else statement will never be reached.
将中断放在 else 子句中,如下所示:
Put the break in the else clause instead, like so:
while True:
try:
x = int(raw_input("Please enter a number: "))
except ValueError:
print "Oops! That was not a valid number. Try again..."
else:
print 'Thanks,',x,'is indeed an integer'
break
print 'all done, bye'
这篇关于while 语句中的 try 块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!