【问题标题】:Returning to a specific point after exception is raised in Python 3在 Python 3 中引发异常后返回特定点
【发布时间】:2014-03-30 20:29:37
【问题描述】:

如果输入了超出指定范围的数字,我的代码会引发异常错误。 这样做后,它会将控制权返回给我的主要功能。

我希望它做的是返回问题,以便用户可以重试。怎么能 我让它返回到另一个输入的变量?

def student_entry():
    try:
        num_students = int(input('How many students do you have? : ' ))
        print()
        for student in range (1, num_students + 1):
            print('enter data for student #', student, sep='')
            print()
            name = input('Student Name: ')
            print()
            average = int(input('What is the students average : '))
            print()

            try:
                if average >=0 and average <= 100:

                    mainfile.write(str('Student Name: ') + str(name) +'\n')
                    mainfile.write(str('Grade Average: ') + str(average) + '\n')

                else:
                    raise ValueError

            except ValueError as AverageError:

                print('invalid average. Please try again.')
                return average

    except ValueError:

        print('an error has occured')

    return

【问题讨论】:

    标签: python exception python-3.x syntax return


    【解决方案1】:

    当您捕获ValueError 时,您正在突破student_entry() 函数,就像您return average. 一样您可以通过使用while 循环来避免这种情况,只有在满足平均条件后才能突破并写出你的数据。

    while True:
        average = int(input('What is the students average : '))
        try:
            if average > 0 and average <= 100:
                # write to file
                break # this will break out of the while loop
            else:
                raise  ValueError
        except ValueError:
               print("Invalid average - try again")
    

    使用while True 将意味着循环将重复运行,直到我们使用break 语句显式中断它 - 因此将提示用户输入输入,直到他们满足其平均值大于零的条件且小于或等于 100。

    有关 Python 中 while 循环的更多详细信息,请参见 https://wiki.python.org/moin/WhileLoop

    【讨论】:

      【解决方案2】:

      尝试将您的输入包装在一个while循环中:

      average = -1
      while (average < 0) or (avergage > 100)
         average = int(input('What is the students average : '))
      print()
      

      您可以在附加条件方面获得更多创意,向您的用户解释输入无效的原因等,但这应该足以让您继续前进。

      【讨论】:

        猜你喜欢
        • 2021-10-28
        • 1970-01-01
        • 2011-09-10
        • 2017-10-16
        • 2020-12-06
        • 2012-03-22
        • 2016-03-18
        • 2020-08-18
        • 1970-01-01
        相关资源
        最近更新 更多