try block inside while statement

江枫思渺然 提交于 2019-12-18 06:59:24

问题


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?


回答1:


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'



回答2:


It is probably because of the break statement, which leaves the loop. The break statement is only reached when there is no exception in the line before.




回答3:


Not a python guy, but how about this

while True:
    try:
        x = int(raw_input("Please enter a number: "))
        print 'Thanks,', x, 'is indeed an integer'
    except ValueError:
        print "Oops!  That was not a valid number. Try again..."
    finally:
        print 'all done, bye'



回答4:


i recently faced a question in which no input, for how many test cases .while loop and try-except are very helpful.

while(True):
try:
    x=(input())
    x1,x2=x.split()
    #print(x1,x2)
    print(int(x1)+int(x2))
except:
    break


来源:https://stackoverflow.com/questions/11758029/try-block-inside-while-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!