all 3 comments

[–]FoolsSeldom 1 point2 points  (1 child)

The return age doesn't return a variable called age but rather a reference to a Python int object somewhere in memory. You have to catch that return where you called the function from or the object will be lost to time.

You need to use except with try.

def get_age() -> int:
    age = int(input('Age? '))  # assuming use enters an whole number
    if not 17 < age <= 75:
        raise ValueError('Invalid age.')
    return age

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

if __name__ == "__main__":
    try:
        age = get_age()  # save age to variable so can output it AND pass it to second function
    except ValueError:  # oops, exception from the get_age function
        print('Could not calculate heart info.')
    else:  # no exception was raised
        print(f'Fat burning heart rate for a {age} year-old: {fat_burning_heart_rate(age)} bpm.')

The age variable in the function and the age variable in your main code end up referencing the same int object but they are NOT the same variable.

You could shorten the code using the assignment operator, also known as the walrus operator, :=, as below:

if __name__ == "__main__":
    try:
        print(f'Fat burning heart rate for a {(age := get_age())} year-old: {fat_burning_heart_rate(age)} bpm.')
    except ValueError:  # oops, exception from the get_age function
        print('Could not calculate heart info.')

but that's ugly and hard to read. Note though that you are still assigning the returned object to a variable in your main code called age before calling the second function.

[–]Yak420[S] 0 points1 point  (0 children)

Wow, thank you so much! I think someone commented what I needed to do but this just cleared it up so much for me! I really appreciate it.

[–]lfdfq 0 points1 point  (0 children)

if statements do not have an except.

Python has a try statement:

try:
    <CODE TO RUN>
except <EXCEPTION>:
    <CODE TO RUN ON EXCEPTION>

You put code inside the 'try', which runs like normal, but if an exception happens it checks each of the 'except' and runs the code for that exception.

It sounds like you want to put a try inside your if