try while里面while语句 [英] try block inside while statement

查看:287
本文介绍了try while里面while语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始用Python 2.7,我不明白为什么会发生什么:



在下面的代码中,一个例子的修饰版本python 2.7.2教程,我得到一个意想不到的结果:

  while True:
try:
x = int(raw_input(请输入一个数字:))
break
除了ValueError:
打印糟糕!这不是有效的数字,再试一次...
else:
print'谢谢,',x''确实是一个整数'
finally:
print'全部完成,bye'
/ pre>

当我放入一个整数时,代码忽略了 else:语句,直接切换到最后:。很明显,这是与顶级的,而True:,但为什么会发生?

解决方案

break语句正在拉出循环,因此将永远不会达到else语句。



将break放在else子句中,像这样:

  while True:
try:
x = int(raw_input(请输入一个数字:))
除了ValueError:
打印糟糕!这不是一个有效的数字,再试一次...
else:
print'谢谢' '确实是一个整数'
break

print'全部完成,bye'


I'm just starting out with Python 2.7 and I don't understand why something is happening:

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'

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?

解决方案

The break statement is pulling out of the loop, so the else statement will never be reached.

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'

这篇关于try while里面while语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆