让Try语句循环直到获得正确值

25 投票
7 回答
170783 浏览
提问于 2025-04-15 19:09

我想让用户输入一个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()

我还遇到了一个关于我输入的异常的错误:

kill.py:20: DeprecationWarning: catching of string exceptions is deprecated
  except 'incorrect':
Error

谢谢大家的帮助

7 个回答

4

你的方法看起来有点繁琐,其实可以用更简单的方式来完成这个事情:

def Release() :
    while True :
        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 0 <= a < 4 :
            files(a)
            break
        else :
            print('Try Again')
6

现代的Python异常其实是类;如果你使用 raise 'incorrect',那是在用一个已经不推荐使用的特性,叫做字符串异常。你可以去看看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)

顺便说一句,a 这个变量名不好;你可能应该把它改成 chosen_option 或者类似的名字。

62

在编程中,有时候我们会遇到一些问题,可能会让我们感到困惑。这些问题通常是因为我们对某些概念不够了解,或者在使用某些工具时没有掌握正确的方法。

比如说,当我们在写代码的时候,可能会出现错误,或者代码运行的结果和我们预期的不一样。这时候,我们就需要仔细检查代码,看看是不是哪里写错了,或者有没有遗漏什么重要的步骤。

此外,学习编程的过程中,遇到问题是很正常的。我们可以通过查阅资料、请教他人或者在网上寻找解决方案来帮助自己解决这些问题。记住,编程是一项需要不断练习和学习的技能,遇到困难时不要气馁,慢慢来,总会找到解决办法的。

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'

撰写回答