【问题标题】:try and except value error , unbound local variable尝试并排除值错误,未绑定的局部变量
【发布时间】:2020-05-10 20:01:31
【问题描述】:

如果输入不等于整数,我将遍历用户的输入。我正在使用try: except value error,我收到一条错误消息:

UnboundLocalError: local variable 'averageHeartRate' referenced before assignment

我认为这意味着我的循环不起作用,它正在进入 if 语句的下一阶段,我该如何解决这个问题,我尝试添加其他 while True: 循环但它们不起作用。

def heartRate():
        while True:
            multiple_zone_question = input('Did you work in multiple heart zones? Answer Y  for "Yes" or N for "No": ')

           " i haven't finished writing this if statement"
            if multiple_zone_question.lower() == 'y':
                print('good')
                break

           " if user stayed only in one heart rate zone during exercise "
            elif multiple_zone_question.lower() == 'n':
                try:

                   "ask user for average heart rate "
                    avarageHeartRate = int(input('What was your Avarage Heart Rate during your exceresice? '))
                except ValueError:
                    print("That's not an int!")

                    " average heart are should be no more then 3 numbers exm: 155 bpm"
                    if avarageHeartRate.len() > 3:
                        print('heart rate should be less then 200::\n Please enter a valid number')

                    '''else avarageHeartRate witch is an integer, multiplied by thresh 
                    hold witch is also an integer stored outside of function (i probably 
                    should move it inside the function right?). this will give me a 
                    percentage (float) witch i can then store it into a SQL table as a 
                    float int'''
                    else:
                        heartZone = avarageHeartRate /threshhold
                        return heartZone

            "if multiple_zone_question is not y or n "
            elif multiple_zone_question.lower() != 'y' or 'n' :
                print("Invalid entry: please enter Y or N")

【问题讨论】:

  • 在您的异常处理程序中,您有if avarageHeartRate.len() > 3。但是如果遇到该异常,则不会设置 avarageHeartRate。顺便说一句,根据您的代码,您希望 avarageHeartRate 是一个整数值,但整数没有 len 方法。

标签: python function try-catch


【解决方案1】:

averageHeartRate 当作整数处理的代码位于except 块内,当输入值不是整数时调用该块,因此永远不会分配给averageHeartRate。您可能应该执行以下操作(注意 else: 声明):

            try:
                avarageHeartRate = int(input('What was your Avarage Heart Rate during your exceresice? '))
            except ValueError:
                print("That's not an int!")
            else:
                if avarageHeartRate.len() > 3:
                    print('heart rate should be less then 200::\n Please enter a valid number')
                # and so on...

【讨论】:

    【解决方案2】:

    我决定在主函数中编写 2 个函数,而不是全部写在一个函数中。如果答案是肯定的,一个将处理,而另一个函数将处理“否”。有点乱,但更容易阅读

        ddef heartRate():
            'i moved the threshold var inside the function'
            threshold = int(183)
            multiple_zone_question = input('Did you work in multiple heart zones? Answer Y  for "Yes" or N for "No": ')
    
            if multiple_zone_question.lower() == 'y':
                def answerYES():
                    pass
    
            elif multiple_zone_question.lower() == 'n':       
                def answerNO():
                    while True:
                       'catch if answer is not a number'
                        try:
                            avaregeHeartRate = int(input('What was your Avarage Heart Rate during your exceresice? '))
                        except ValueError:
                            print('answer must be a number: Try Again')
                        'makes sure answer is less then 200. '
                        else:
                            if avaregeHeartRate > 200:
                                print('heart rate should be less then 200')
                            'if there is no problems we can then find the heart zone'
                            else:
                                heart_zone = avaregeHeartRate /threshold
                                'i added a round() to simplify the float number'
                                return round(heart_zone, 2)
                                break
    
            elif multiple_zone_question.lower() != 'y' or 'n' :
                print("Invalid entry: please enter Y or N")
    

    我的大脑告诉我 lambda 函数,要简化。一旦我弄清楚如何做,我会让它更 Pythonic

    【讨论】:

      猜你喜欢
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2012-10-14
      • 1970-01-01
      • 2011-08-15
      • 1970-01-01
      相关资源
      最近更新 更多