Python try exception

Hello,

I have been having issues with this task as well. I am getting an UnboundLocalError for my try/except statement when I call the function it is in.

This is the code I have been using, which from what I can tell, is almost identical to the example given above. The only difference I noticed was that my print statement used the .format() function.

### Creating a Class called Patient that takes specific demographic inputs, and can perform various functions (e.g. calculate estimated insurance costs, update various inputs, create a dictionary of the patient information etc.)
class Patient:
  def __init__(self, name, age, sex, bmi, num_of_children, smoker):
    self.name = name
    self.age = age
    self.sex = sex
    self.bmi = bmi
    self.num_of_children = num_of_children
    self.smoker = smoker
### Function to estimate insurance cost, and print a reminder when an input other than 'name' isn't an integer (or float).
  def estimated_insurance_cost(self):
    try:
      estimated_cost = 250 * self.age - 128 * self.sex + 370 * self.bmi + 425 * self.num_of_children + 24000 * self.smoker - 12500
    except TypeError:
      print("Input should be an integer or float.")
    print("{}'s estimated insurance costs is {} dollars.".format(self.name, estimated_cost))
### Function to update age
  def update_age(self, new_age):
    self.age = new_age
    print("{} is now {} years old.".format(self.name, self.age))
### Function to update the number of children, and print a grammmatically correct statement about the number of children the patient has
  def update_num_children(self, new_num_children):
    self.num_of_children = new_num_children
    if self.num_of_children == 1:
      print("{} has {} child.".format(self.name, self.num_of_children))
    else:
      print("{} has {} children.".format(self.name, self.num_of_children))
### Function to update the patients BMI
  def update_bmi(self, new_bmi):
    self.bmi = new_bmi
### Function to update the patients smoking status
  def update_smoking_status(self, new_smoking_status):
    self.smoker = new_smoking_status
### Function to create a dictionary of the patients information, with appropriate key:value pairs
  def patient_profile(self):
    patient_information = {}
    patient_information["Name"] = self.name
    patient_information["Age"] = self.age
    patient_information["Sex"] = self.sex
    patient_information["BMI"] = self.bmi
    patient_information["Number of Children"] = self.num_of_children
    patient_information["Smoker"] = self.smoker
    return patient_information
    
### Creating an object with the Patient Class
patient1 = Patient("John Doe", 25, 1, 22.2, 0, 0)
print(patient1.name, patient1.age, patient1.sex, patient1.bmi, patient1.num_of_children, patient1. smoker)

### Using the various functions in the class on a specific instantiation of the class, then testing how they effect the estimated insurance cost function.
patient1.estimated_insurance_cost()
patient1.update_age(26)
patient1.estimated_insurance_cost()
patient1.update_num_children(1)
patient1.estimated_insurance_cost()
print(patient1.patient_profile())

### Creating a second object with the Patient Class, but providing an alternate input that should throw a type error for the try/except statement when the estimated insurance cost function is called (due to the 'age' variable being a string instead of an integer)
patient2 = Patient("Wimp Lo", "24", 1, 23.6, 0, 1)
patient2.estimated_insurance_cost()

From what I’ve been able to search, I think the issue is that the estimated_cost variable didn’t initialize, so that when I call it in the .format() function, it can’t be found. I’m not sure why the estimated_cost variable hasn’t been assigned anything within the local scope of the function, as the line before the except statement is literally doing that. The code worked worked fine prior to me adding the try/except statement in, so I’m unsure as to what is happening.

Any hints would be greatly appreciated.

1 Like

but if the exception occurs, the variable can’t be named/assigned.

If you remove the try/except your program will crash with an error.

patient1 has valid data, then everything is fine. But then you added another patient (patient2), which has invalid data. Which is why we needed the exception handling

2 Likes

Ohhhh, I get it. I don’t know why I assumed I wouldn’t get an error once the exception worked. I guess I kind of assumed it would print the “Input should be an integer or float.” statement, then just not output anything for the estimated insurance cost function for patient2. I should probably have more coffee…

Thanks a lot for the help!

1 Like

Normally exception are thrown/raised when to terminated the program. If we handle the exception, the program continues running. So you have to be careful when handling exceptions

you can do something along these lines:

  def estimated_insurance_cost(self):
    try:
      estimated_cost = 250 * self.age - 128 * self.sex + 370 * self.bmi + 425 * self.num_of_children + 24000 * self.smoker - 12500
      print("{}'s estimated insurance costs is {} dollars.".format(self.name, estimated_cost))
    except TypeError:
      print("Input should be an integer or float.")

now if an exception occurs on the line that calculate the estimated cost, the code will go out of the try block and only print the error message

2 Likes