'I'm having trouble with this

def get_age():
    age = int(input())
    if age < 18 or age > 75:
        raise ValueError('Invalid age.')
    return age


def fat_burning_heart_rate(age):

    heart_rate = (220 * 0.70) - age
    return heart_rate

if __name__ == "__main__":
    try:
        heart_rate = fat_burning_heart_rate(age)
        age = get_age()
        print('Fat burning heart rate for a', age, 'year-old:', 
               heart_rate, 'bpm')

    except ValueError as e:
        print(e)
        print('Could not calculate heart rate info.')

The primary issue that I have so far is when I go run this code it generates a name error saying that 'age' is not defined. This occurs when I try to assign heart_rate = fat_burning_heart_rate(age). I suspect that it has something to do with the way that I pass the function parameter. But what can I do to fix it?



Solution 1:[1]

def fat_burning_heart_rate(age):

heart_rate = (220 * 0.70) - age
if age < 18 or age > 75:
    raise ValueError('Invalid age.')
return heart_rate, age

if __name__ == "__main__":
  try:
    age = int(input("Input age: "))
    heart_rate, age = fat_burning_heart_rate(age)
    print('Fat burning heart rate for a', age, 'year-old:',
          heart_rate, 'bpm')

except ValueError as e:
    print(e)
    print('Could not calculate heart rate info.') 

You don't need get_age(). You can add that code to fat_burning_heart_rate().

Solution 2:[2]

age = get_age() seemed to be in the wrong position within the code, also I believe you misinterpreted the expression for heart rate. This code will allow for both definitions and will properly flag any errors.

def get_age():
    age = int(input())
    if age < 18 or age > 75:
        raise ValueError('Invalid age.')
    return age

def fat_burning_heart_rate(age):
    heart_rate = (220 - age) * .7
    return heart_rate


if __name__ == "__main__":
    try:
        age = get_age()
        heart_rate = fat_burning_heart_rate(age)
        print('Fat burning heart rate for a', age, 'year-old:', 
heart_rate, 'bpm')

    except ValueError as e:
        print(e)
        print('Could not calculate heart rate info.')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joshua Santiago
Solution 2 Jakob Taylor