try block inside while statement

前端 未结 4 1322
小鲜肉
小鲜肉 2020-12-17 01:54

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 pytho

相关标签:
4条回答
  • 2020-12-17 02:05

    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'
    
    0 讨论(0)
  • 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(int(x1)+int(x2))
        except:
            break
    
    0 讨论(0)
  • 2020-12-17 02:22

    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.

    0 讨论(0)
  • 2020-12-17 02:22

    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'
    
    0 讨论(0)
提交回复
热议问题