获取Try语句以循环直到获得正确的值

chr*_*ley 13 python loops exception-handling try-catch

我试图让用户输入1到4之间的数字.我有代码检查数字是否正确,但我希望代码循环几次,直到数字正确.有谁知道如何做到这一点?代码如下:

def Release():


    try:
        print 'Please select one of the following?\nCompletion = 0\nRelease ID = 1\nVersion ID = 2\nBuild ID = 3\n'
        a = int(input("Please select the type of release required: "))
        if a == 0:
            files(a)
        elif a == 1:
            files(a)
        elif a == 2:
            files(a)
        elif a == 3:
            files(a)
        else:
            raise 'incorrect'
    except 'incorrect':    
        print 'Try Again'
    except:
        print 'Error'

Release()
Run Code Online (Sandbox Code Playgroud)

我也收到了关于我输入的异常的错误:

kill.py:20: DeprecationWarning: catching of string exceptions is deprecated
  except 'incorrect':
Error
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助

Joh*_*rra 39

def files(a):
    pass

while True:
    try:
        i = int(input('Select: '))
        if i in range(4):
            files(i)
            break
    except:    
        pass

    print '\nIncorrect input, try again'
Run Code Online (Sandbox Code Playgroud)


Han*_*Gay 5

现代Python异常是类; 通过使用raise 'incorrect',您使用了一种名为字符串异常的已弃用语言功能.Python教程的错误和异常部分是从Python中基本异常处理开始的好地方.

一般来说,异常并不适合您的情况 - 简单的while循环就足够了.应该为例外情况保留例外情况,并且不良用户输入也不是例外,这是预期的.

基于循环的版本Release看起来像这样:

def Release():
    a = None
    while a not in (0, 1, 2, 3):
        print 'Please select one of the following?\nCompletion = 0\nRelease ID = 1\nVersion ID = 2\nBuild ID = 3\n'
        try:
            a = int(input("Please select the type of release required: "))
        except ValueError:
            pass  # Could happen in face of bad user input
    files(a)
Run Code Online (Sandbox Code Playgroud)

PS a是一个糟糕的变量名; 你可能应该改成它chosen_option或类似的东西.