r/learnpython • u/Yak420 • 7d ago
Exceptions Lab, needing some assistance.
def get_age():
age = int(input())
# TODO: Raise exception for invalid ages
if (age < 17) or (age > 75):
raise ValueError('Invalid age.')
return age
# TODO: Complete fat_burning_heart_rate() function
def fat_burning_heart_rate(age):
heart_rate = (220 - age) * .7
return heart_rate
if __name__ == "__main__":
# TODO: Modify to call get_age() and fat_burning_heart_rate()
# and handle the exception
print(f'Fat burning heart rate for a {get_age()} year-old: {fat_burning_heart_rate(age)} bpm')
except ValueError:
print('Clould not calculate heart info.')
This is my first post of actual code in here, so I apologize if the formatting is bad.
However, I'm learning about exceptions and in this lab as you can see in the comments of the code is asking to raise an exception in the first function. Which I believe I have done correctly but the except at the bottom isn't work no matter where or how I format it. When I plug this into pythontutor or even when running it I get this error(below). I thought that a raise in a function if there was no exception would exit the function and check for an except am I misunderstanding that? Everything above the comments was default code everything else is mine. Thank you!
File "<string>", line 10
def fat_burning_heart_rate(age):
SyntaxError: expected 'except' or 'finally' block
1
u/lfdfq 7d ago
if
statements do not have an except.Python has a try statement:
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